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'isAuthorized, (reqres=> {
    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', (reqres=> {
    res.json({ "message" : "This is open to the world!" })
})

app.get('/jwt', (reqres=> {
    let privateKey = fs.readFileSync('./private.pem''utf8');
    let token = jwt.sign({ "body": "stuff" }, privateKeyalgorithm: 'HS256'});
    res.send(token);
})

function isAuthorized(reqresnext) {
    if (typeof req.headers.authorization !== "undefined") {
        // retrieve the authorization header and parse out the
        // JWT using the split function
        let token = req.headers.authorization.split(" ")[1];
        
        let privateKey = fs.readFileSync('./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(tokenprivateKey, { algorithm: "HS256" }, (erruser=> {
            
            // 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-----
MIIEpAIBAAKCAQEAyVTQ9QxfutaYXKBbYfZbH2vhIWoIPEjAFSbsy1PZoIcclUQR
hJ8t2m7v47M8eEyYd7EvXTNdoN6CDs0DoNC9KESATZ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d7xofDexug5m65eVFkETNtKHAJK6mPbiCKs87/AmhQWx1gV6
iNRHv+ns5RiBka6/3A3oG0ECgYEAl+qIO0rqaG++1ozHTArSCl4DUlkkYQhLe56p
OSYASRE9WF/eM0DM0eHPGGahdC42OfE1cCOYH7WDa5mtGB0ggHxMKjsj2tk+kpFS
1D9SHjx24JShCiAfonNVjQfRr6KjwwKnKAzI+Z8ljRCikmLN9A5rPegvPE1by++/
i132TIECgYAiDd+OSokfZYi8mqjIoMI946+Hlb7lisb7CXksM69A+oWJrfkCwOMq
O3tExLbxtd7KZuAg1xH2thimIeT6tuCbCSAFGzr4EWCe7iavVzevHr98ivPLYXte
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: Stringrequired: true },
        userPassword: { type: Stringrequired: true }
    },
    { timestamps: true },
)

module.exports = mongoose.model('user'User);

After then create controller file as user-model.js:
controller.js
const jwt = require('jsonwebtoken');
const fs = require('fs')

getUsers = async (reqres=> {
    var params=req.body;
    
    await Users.find({userEmail: params.emailuserPassword: params.password}, (errresult=> {
        if (err) {
            return res.status(400).json({ success: falseerror: err })
        }
        if (!result.length) {
            return res
                .status(404)
                .json({ success: falseerror: `Users not found` })
        }
        let privateKey = fs.readFileSync('./private.pem''utf8');
        let token = jwt.sign({ "body": req.params.email }, privateKey, { algorithm: 'HS256'});

        return res.status(200).json({ success: truedata: token })
    }).catch(err => console.log(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 } from "react";
import { apiBaseUrl } from '../../assets/js/helpers'
import axios from 'axios';

export default function Login(props) {
    const [emailsetEmail] = useState("");
    const [passwordsetPassword] = useState("");
    const [userDatasetUserData] = useState([]);

    function validateForm() {
        return email.length > 0 && password.length > 0;
    }

    function handleSubmit(event) {
        event.preventDefault();
        axios.post(apiBaseUrl 'api/users', { email: email, password: password })
            .then(response => {
                setUserData(response.data.data);

                if (response.data.success) {
                    window.localStorage.setItem('token'response.data.data);
                    props.history.push("/dashboard");
                }
                else {
                    props.history.push("/login");
                }
console.log(response.data.data)
            
}, error => {
                console.log(error)
            })

    }

    return (
        <div className="container">
            <form>
                <div className="form-group">
                    <label>Email address</label>
                    <input type="email" className="form-control" aria-describedby="emailHelp" placeholder="Enter email" autoFocus
                        value={email} onChange={e => setEmail(e.target.value)} />
                </div>
                <div className="form-group">
                    <label>Password</label>
                    <input type="password" className="form-control" placeholder="Password" value={password}
                        onChange={e => setPassword(e.target.value)} />
                </div>
                <Button block disabled={!validateForm()} onClick={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.localStorage.getItem('token');
        // for login
        if (window.localStorage.getItem('token') === null) {
            props.history.push('/login');
        }
        else {
            axios.get(apiBaseUrl + 'secret', { headers: { "Authorization": `Bearer ${token}` } })
                .then(response => {
                    console.log(response.data.data)
                }, error => {
                    window.localStorage.clear();
                    props.history.push('/login');
                })
        }

    }
 
You will be found results:
 

No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.