How to implement jwt token in react?
JWT authentication
with React: why we need to token?
Jwt token is the best for the login it provides a generated token when we will log in again and again then it generates new token with the private.pem file.
.pem Stands for the: Privacy
Enhanced Mail
This file has some
key and it's generating randomly token and if we change anything else in the
local storage area then it's created an error and you can't share or modify this
token because this token generates in the run time.
We run in the node the server where is available your API, need to follow the step to step: for the jwt
installing: use below command:
$ npm install
jsonwebtoken
After then need to
import where is your main app file as app.js where you have imported your
express as below example:
const express = require(' express')
const bodyParser = require(' body-parser')
const cors = require('cors')
const jwt = require(' jsonwebtoken');
const fs = require('fs')
Need to add this code in this
file:
// jwt implementation
// let's first add a /secret api endpoint that we will be protecting
app.get('/secret', isAuthorize d, (req, res) => {
res.json({ "message" : " THIS IS SUPER SECRET, DO NOT SHARE!" })
})
// and a /readme endpoint which will be open for the world to see
app.get('/readme', (req, res) => {
res.json({ "message" : " This is open to the world!" })
})
app.get('/jwt', (req, res) => {
let privateKey = fs.readFi leSync('./private.pem', 'utf8' );
let token = jwt.sign({ " body": "stuff" }, privateKey, { algorithm: 'HS256'});
res.send(token);
})
function isAuthorized(req, res , next) {
if (typeof req.headers.aut horization !== "undefined") {
// retrieve the authorization header and parse out the
// JWT using the split function
let token = req.header s.authorization.split(" ")[1];
let privateKey = fs.re adFileSync('./private.pem', ' utf8');
// Here we validate that the JSON Web Token is valid and has been
// created using the same private pass phrase
jwt.verify(token, priv ateKey, { algorithm: "HS256" } , (err, user) => {
// if there has been an error...
if (err) {
// shut them out!
res.status(500 ).json({ error: "Not Authorized" });
}
// if the JWT is valid, allow them to hit
// the intended endpoint
return next();
});
} else {
// No authorization header exists on the incoming
// request, return not authorized
res.status(500).json({ error: "Not Authorized" });
}
}
After then create this file
in the root, code is below:
private.pem
-----BEGIN RSA
PRIVATE KEY-----
MIIEpAIBAAKCAQEAyVTQ9QxfutaYXK BbYfZbH2vhIWoIPEjAFSbsy1PZoIcc lUQR
hJ8t2m7v47M8eEyYd7EvXTNdoN6CDs 0DoNC9KESATZV5SUVr7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7pzK
ZAICKJ7THfrz4VX5d7xofDexug5m65 eVFkETNtKHAJK6mPbiCKs87/ AmhQWx1gV6
iNRHv+ns5RiBka6/3A3oG0ECgYEAl+ qIO0rqaG++ 1ozHTArSCl4DUlkkYQhLe56p
OSYASRE9WF/ eM0DM0eHPGGahdC42OfE1cCOYH7WDa 5mtGB0ggHxMKjsj2tk+kpFS
1D9SHjx24JShCiAfonNVjQfRr6Kjww KnKAzI+ Z8ljRCikmLN9A5rPegvPE1by++/
i132TIECgYAiDd+ OSokfZYi8mqjIoMI946+ Hlb7lisb7CXksM69A+oWJrfkCwOMq
O3tExLbxtd7KZuAg1xH2thimIeT6tu CbCSAFGzr4EWCe7iavVzevHr98ivPL YXte
dyWl3YlvqO+SUuieGvHISlekblMO/ 4tcUscmKmo+FgkMroBsePcdEA==
-----END RSA PRIVATE
KEY-----
After then create new file as
user-model.js:
user-model.js
const mongoose = require(' mongoose')
const Schema = mongoose.Schema
const User = new Schema(
{
id: { type: String},
userEmail: { type: Str ing, required: true },
userPassword: { type: String, required: true }
},
{ timestamps: true },
)
module.exports = mongoose.mode l('user', User);
After then create controller
file as user-model.js:
controller.js
const jwt = require(' jsonwebtoken');
const fs = require('fs')
getUsers = async (req, res) => {
var params=req.body;
await Users.find({userEmai l: params.email, userPassword: params.password}, (err, resul t) => {
if (err) {
return res.status( 400).json({ success: false, er ror: err })
}
if (!result.length) {
return res
.status(404)
.json({ succes s: false, error: `Users not found` })
}
let privateKey = fs.re adFileSync('./private.pem', ' utf8');
let token = jwt.sign({ "body": req.params.email }, p rivateKey, { algorithm: ' HS256'});
return res.status(200) .json({ success: true, data: t oken })
}).catch(err => console.lo g(err))
}
module.exports = {
getUsers
}
After then need to where is
your router as below:
Router.js
const express = require(' express')
const yourCtrl = require('./ controller')
const router = express.Router( )
router.post('/Users', yourCtrl .getUsers)
module.exports = router
Now need to go in the react project where you need to get your
token create login.js
import React, { useState } fro m "react";
import { apiBaseUrl } from '.. /../assets/js/helpers'
import axios from 'axios';
export default function Login( props) {
const [email, setEmail] = useState("");
const [password, setPasswo rd] = useState("");
const [userData, setUserDa ta] = useState([]);
function validateForm() {
return email.length > 0 && password.length > 0;
}
function handleSubmit(even t) {
event.preventDefault() ;
axios.post(apiBaseUrl + 'api/users', { email: email, password: password })
.then(response => {
setUserData(re sponse.data.data);
if (response.d ata.success) {
window.loc alStorage.setItem('token', res ponse.data.data);
props.hist ory.push("/dashboard");
}
else {
props.hist ory.push("/login");
}
console.log(response.data.data )
}, error => {
console.log(er ror)
})
}
return (
<div className=" container">
<form>
<div className ="form-group">
<label>Ema il address</label>
<input typ e="email" className="form- control" aria-describedby=" emailHelp" placeholder="Enter email" autoFocus
value= {email} onChange={e => setEmai l(e.target.value)} />
</div>
<div className ="form-group">
<label>Pas sword</label>
<input typ e="password" className="form- control" placeholder=" Password" value={password}
onChan ge={e => setPassword(e.target. value)} />
</div>
<Button block disabled={!validateForm()} onC lick={handleSubmit} type=" submit">Login</Button>
</form>
</div>
)
}
For the validation when
page loaded then check this page already login or the not login so add some
code on the constructor in the react:
constructor(props) {
super(props);
var token = window.loc alStorage.getItem('token');
// for login
if (window.localStorag e.getItem('token') === null) {
props.history.push ('/login');
}
else {
axios.get(apiBaseU rl + 'secret', { headers: { " Authorization": `Bearer ${toke n}` } })
.then(response => {
console.lo g(response.data.data)
}, error => {
window.loc alStorage.clear();
props.hist ory.push('/login');
})
}
}
You will be found results:
No comments:
Note: Only a member of this blog may post a comment.