Poppy Cooke

Poppy Cooke

1560242684

React (without Redux) - JWT Authentication Tutorial & Example

In this tutorial we’ll go through an example of how you can implement JWT authentication in React (without Redux). I posted another version a while back with redux and thought it would be helpful to post an updated version showing how it can be done without redux.

The tutorial example is pretty minimal and contains just 2 pages to demonstrate JWT authentication in React - a login page and a secure home page.

Running the React JWT Authentication Example Locally

The tutorial example uses Webpack 4 to transpile the React code and bundle the modules together, and the webpack dev server is used as the local web server, to learn more about using webpack you can check out the official webpack docs.

  1. Install NodeJS and NPM from https://nodejs.org/en/download/.
  2. Download or clone the tutorial project source code from https://github.com/cornflourblue/react-jwt-authentication-example
  3. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  4. Start the application by running npm start from the command line in the project root folder.
  5. Your browser should automatically open at [http://localhost:8080](http://localhost:8080) with the login page of the demo React JWT authentication app displayed.

Running the Tutorial Example with a Real Backend API

The React JWT authentication example app uses a fake / mock backend by default so it can run in the browser without a real api, to switch to a real backend api you just have to remove or comment out the 2 lines below the comment // setup fake backend located in the /src/index.jsx file.

React JWT Authentication Project Structure

All source code for the React JWT authentication tutorial is located in the /src folder. Inside the src folder there is a folder per feature (App, HomePage, LoginPage) and few folders for non-feature code that can be shared across different parts of the app (_components, _helpers, _services).

I prefixed non-feature folders with an underscore “_” to group them together and make it easy to distinguish between features and non-features, it also keeps the project folder structure shallow so it’s quick to see everything at a glance from the top level and to navigate around the project.

The index.js files in each folder are barrel files that group the exported modules from a folder together so they can be imported using the folder path instead of the full module path and to enable importing multiple modules in a single import (e.g. import { userService, authenticationService } from '@/_services').

A path alias ‘@’ has been configured in the webpack.config.js that maps to the ‘/src’ directory. This allows imports to be relative to the ‘/src’ folder by prefixing the import path with ‘@’, removing the need to use long relative paths like import MyComponent from '../../../MyComponent'.

Click any of the below links to jump down to a description of each file along with it’s code:

React Tutorial Components Folder

Path: /src/_components

The _components folder contains shared React components that can be used anywhere in the application.

React Tutorial Private Route Component

Path: /src/_components/PrivateRoute.jsx

The react private route component renders a route component if the user is logged in, if the user isn’t logged in they are redirected to the /login page.

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

import { authenticationService } from '@/_services';

export const PrivateRoute = ({ component: Component, ...rest }) => (
     {
        const currentUser = authenticationService.currentUserValue;
        if (!currentUser) {
            // not logged in so redirect to login page with the return url
            return 
        }

        // authorised so return component
        return 
    }} />
)

React Tutorial Helpers Folder

Path: /src/_helpers

The helpers folder contains all the bits and pieces that don’t fit into other folders but don’t justify having a folder of their own.

React Tutorial Auth Header

Path: /src/_helpers/auth-header.js

Auth header is a helper function that returns an HTTP Authorization header containing the JWT auth token of the currently logged in user. If the user isn’t logged in an empty object is returned.

The auth header is used to make authenticated HTTP requests to the server api using JWT authentication.

import { authenticationService } from '@/_services';

export function authHeader() {
    // return authorization header with jwt token
    const currentUser = authenticationService.currentUserValue;
    if (currentUser && currentUser.token) {
        return { Authorization: `Bearer ${currentUser.token}` };
    } else {
        return {};
    }
}

React Tutorial Fake / Mock Backend

Path: /src/_helpers/fake-backend.js

The fake backend enables the example to run without a backend (backend-less), it contains a hardcoded collection of users and provides fake implementations for the api endpoints “authenticate” and “get all users”, these would be handled by a real api and database in a production application.

The “authenticate” endpoint is used for logging in to the application and is publicly accessible, the “get all users” endpoint is restricted to users that are logged in.

The fake backend is implemented by monkey patching the fetch() function to intercept certain api requests and mimic the behaviour of a real api. Any requests that aren’t intercepted get passed through to the real fetch() function.

export function configureFakeBackend() {
    let users = [{ id: 1, username: 'test', password: 'test', firstName: 'Test', lastName: 'User' }];
    let realFetch = window.fetch;
    window.fetch = function (url, opts) {
        const isLoggedIn = opts.headers['Authorization'] === 'Bearer fake-jwt-token';

        return new Promise((resolve, reject) => {
            // wrap in timeout to simulate server api call
            setTimeout(() => {
                // authenticate - public
                if (url.endsWith('/users/authenticate') && opts.method === 'POST') {
                    const params = JSON.parse(opts.body);
                    const user = users.find(x => x.username === params.username && x.password === params.password);
                    if (!user) return error('Username or password is incorrect');
                    return ok({
                        id: user.id,
                        username: user.username,
                        firstName: user.firstName,
                        lastName: user.lastName,
                        token: 'fake-jwt-token'
                    });
                }

                // get users - secure
                if (url.endsWith('/users') && opts.method === 'GET') {
                    if (!isLoggedIn) return unauthorised();
                    return ok(users);
                }

                // pass through any requests not handled above
                realFetch(url, opts).then(response => resolve(response));

                // private helper functions

                function ok(body) {
                    resolve({ ok: true, text: () => Promise.resolve(JSON.stringify(body)) })
                }

                function unauthorised() {
                    resolve({ status: 401, text: () => Promise.resolve(JSON.stringify({ message: 'Unauthorised' })) })
                }

                function error(message) {
                    resolve({ status: 400, text: () => Promise.resolve(JSON.stringify({ message })) })
                }
            }, 500);
        });
    }
}

React Tutorial Handle Response

Path: /src/_helpers/handle-response.js

The handleResponse function checks responses from the api to see if the request was unauthorised, forbidden or unsuccessful.

If the response status is 401 Unauthorized or 403 Forbidden then the user is automatically logged out of the application, this handles if the user token is no longer valid for any reason. If the response contains an error then a rejected promise is returned that includes the error message, otherwise if the request was successful then the response data is returned as a JSON object.

import { authenticationService } from '@/_services';

export function handleResponse(response) {
    return response.text().then(text => {
        const data = text && JSON.parse(text);
        if (!response.ok) {
            if ([401, 403].indexOf(response.status) !== -1) {
                // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
                authenticationService.logout();
                location.reload(true);
            }

            const error = (data && data.message) || response.statusText;
            return Promise.reject(error);
        }

        return data;
    });
}

React Tutorial History

Path: /src/_helpers/history.js

The history is a custom history object used by the React Router, the reason I used a custom history object instead of the one built into React Router is to enable redirecting users from outside React components, for example in the logout method of the App component.

import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

React Tutorial Services Folder

Path: /src/_services

The _services layer handles all http communication with backend apis for the application, each service encapsulates the api calls for a content type (e.g. users) and exposes methods for performing various operations (e.g. CRUD operations). Services can also have methods that don’t wrap http calls, for example the authenticationService.logout() method just removes the currentUser object from localStorage and sets it to null in the application.

I like wrapping http calls and implementation details in a services layer because it provides a clean separation of concerns and simplifies the react components that use the services.

React Tutorial Authentication Service

Path: /src/_services/authentication.service.js

The authentication service is used to login and logout of the application, to login it posts the user’s credentials to the /users/authenticate route on the api, if authentication is successful the user details including the token are added to local storage, and the current user is set in the application by calling currentUserSubject.next(user);.

RxJS subjects and observables are used by the service to store the current user state and communicate between different components in the application.

The logged in user details are stored in local storage so the user will stay logged in if they refresh the browser and also between browser sessions until they explicitly logout. If you don’t want the user to stay logged in between refreshes or sessions the behaviour could easily be changed by storing user details somewhere less persistent such as session storage which would persist between refreshes but not browser sessions, or you could remove the calls to localStorage which would cause the user to be logged out if the browser is refreshed.

There are two properties exposed by the authentication service for accessing the currently logged in user. The currentUser observable can be used when you want a component to reactively update when a user logs in or out, for example in the App.jsx component so it can show/hide the main nav bar when the user logs in/out. The currentUserValue property can be used when you just want to get the current value of the logged in user but don’t need to reactively update when it changes, for example in the PrivateRoute.jsx component which restricts access to routes by checking if the user is currently logged in.

import { BehaviorSubject } from 'rxjs';

import config from 'config';
import { handleResponse } from '@/_helpers';

const currentUserSubject = new BehaviorSubject(JSON.parse(localStorage.getItem('currentUser')));

export const authenticationService = {
    login,
    logout,
    currentUser: currentUserSubject.asObservable(),
    get currentUserValue () { return currentUserSubject.value }
};

function login(username, password) {
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
    };

    return fetch(`${config.apiUrl}/users/authenticate`, requestOptions)
        .then(handleResponse)
        .then(user => {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('currentUser', JSON.stringify(user));
            currentUserSubject.next(user);

            return user;
        });
}

function logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    currentUserSubject.next(null);
}

React Tutorial User Service

Path: /src/_services/user.service.js

The user service contains just a couple of methods for retrieving user data from the api, it acts as the interface between the Angular application and the backend api.

I included the user service to demonstrate accessing secure api endpoints with the http authorization header set after logging in to the application, the auth header is set with a JWT token in the auth-header.js helper above. The secure endpoints in the example are fake/mock routes implemented in the fake-backend.js helper above.

import config from 'config';
import { authHeader, handleResponse } from '@/_helpers';

export const userService = {
    getAll
};

function getAll() {
    const requestOptions = { method: 'GET', headers: authHeader() };
    return fetch(`${config.apiUrl}/users`, requestOptions).then(handleResponse);
}

React Tutorial App Folder

Path: /src/App

The app folder is for react components and other code that is used only by the app component in the tutorial application.

React Tutorial App Component

Path: /src/App/App.jsx

The app component is the root component for the react tutorial example, it contains the outer html, routes and main nav bar for the example app.

It subscribes to the currentUser observable in the authentication service so it can reactively show/hide the main navigation bar when the user logs in/out of the application. I didn’t worry about unsubscribing from the observable here because it’s the root component of the application, so the only time the component will be destroyed is when the application is closed which would destroy any subscriptions as well.

The app component contains a logout() method which is called from the logout link in the main nav bar to log the user out and redirect them to the login page.

import React from 'react';
import { Router, Route, Link } from 'react-router-dom';

import { history } from '@/_helpers';
import { authenticationService } from '@/_services';
import { PrivateRoute } from '@/_components';
import { HomePage } from '@/HomePage';
import { LoginPage } from '@/LoginPage';

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            currentUser: null
        };
    }

    componentDidMount() {
        authenticationService.currentUser.subscribe(x => this.setState({ currentUser: x }));
    }

    logout() {
        authenticationService.logout();
        history.push('/login');
    }

    render() {
        const { currentUser } = this.state;
        return (
            
                
                    {currentUser &&
                        
                            
                                Home
                                Logout
                            
                        
                    }
                    
                        
                            
                                
                                    
                                    
                                
                            
                        
                    
                
            
        );
    }
}

export { App };

React Tutorial Home Page Folder

Path: /src/HomePage

The home page folder is for react components and other code that is used only by the home page component in the tutorial application.

React Tutorial Home Page Component

Path: /src/HomePage/HomePage.jsx

The home page component is displayed after signing in to the application, it contains a simple welcome message and a list of all users. The component gets the current user from the authentication service and then fetches all users from the api by calling the userService.getAll() method from the componentDidMount() react lifecycle hook.

import React from 'react';

import { userService, authenticationService } from '@/_services';

class HomePage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            currentUser: authenticationService.currentUserValue,
            users: null
        };
    }

    componentDidMount() {
        userService.getAll().then(users => this.setState({ users }));
    }

    render() {
        const { currentUser, users } = this.state;
        return (
            
                # Hi {currentUser.firstName}!

                
You're logged in with React & JWT!!

                ### Users from secure api end point:

                {users &&
                    
                        {users.map(user =>
                            {user.firstName} {user.lastName}
                        )}
                    
                }
            
        );
    }
}

export { HomePage };

React Tutorial Login Page Folder

Path: /src/LoginPage

The login page folder is for react components and other code that is used only by the login page component in the tutorial application.

React Tutorial Login Page Component

Path: /src/LoginPage/LoginPage.jsx

The login page component contains a login form with username and password fields. It displays validation messages for invalid fields when the user attempts to submit the form or when a field is touched. If the form is valid the component calls the authenticationService.login(username, password) method, if login is successful the user is redirected back to the original page they were trying to access.

I built the login form using Formik, a higher order component that helps with managing form state, validation, error messages, and form submission. Validation is done with the Yup object schema validator which hooks into Formik via the handy validationSchema prop.

import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

import { authenticationService } from '@/_services';

class LoginPage extends React.Component {
    constructor(props) {
        super(props);

        // redirect to home if already logged in
        if (authenticationService.currentUserValue) { 
            this.props.history.push('/');
        }
    }

    render() {
        return (
            
                
                    Username: test

                    Password: test
                
                ## Login

                <Formik
                    initialValues={{
                        username: '',
                        password: ''
                    }}
                    validationSchema={Yup.object().shape({
                        username: Yup.string().required('Username is required'),
                        password: Yup.string().required('Password is required')
                    })}
                    onSubmit={({ username, password }, { setStatus, setSubmitting }) => {
                        setStatus();
                        authenticationService.login(username, password)
                            .then(
                                user => {
                                    const { from } = this.props.location.state || { from: { pathname: "/" } };
                                    this.props.history.push(from);
                                },
                                error => {
                                    setSubmitting(false);
                                    setStatus(error);
                                }
                            );
                    }}
                    render={({ errors, status, touched, isSubmitting }) => (
                        
                            
                                Username
                                
                                
                            
                            
                                Password
                                
                                
                            
                            
                                Login
                                {isSubmitting &&
                                    ![](data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==)
                                }
                            
                            {status &&
                                {status}

                            }
                        
                    )}
                />
            
        )
    }
}

export { LoginPage };

React Tutorial Index HTML File

Path: /src/index.html

The base index html file contains the outer html for the whole tutorial application. When the app is started with npm start, Webpack bundles up all of the react code into a single javascript file and injects it into the body of the page.




    
    React - JWT Authentication Tutorial & Example

    
    

    


    



React Tutorial Main Entry File

Path: /src/index.jsx

The root index.jsx file bootstraps the react tutorial application by rendering the App component into the app div element defined in the base index html file above.

The boilerplate application uses a fake / mock backend by default, to switch to a real backend api simply remove the fake backend code below the comment // setup fake backend.

import React from 'react';
import { render } from 'react-dom';

import { App } from './App';

// setup fake backend
import { configureFakeBackend } from './_helpers';
configureFakeBackend();

render(
    ,
    document.getElementById('app')
);

React Tutorial Babel RC (Run Commands)

Path: /.babelrc

The babel config file defines the presets used by babel to transpile the React and ES6 code. The babel transpiler is run by webpack via the babel-loader module configured in the webpack.config.js file below.

{
    "presets": [
        "@babel/preset-react",
        "@babel/preset-env"
    ]
}

React Tutorial Package.json

Path: /package.json

The package.json file contains project configuration information including package dependencies which get installed when you run npm install. Full documentation is available on the npm docs website.

{
    "name": "react-jwt-authentication-example",
    "version": "1.0.0",
    "repository": {
        "type": "git",
        "url": "https://github.com/cornflourblue/react-jwt-authentication-example.git"
    },
    "license": "MIT",
    "scripts": {
        "start": "webpack-dev-server --open"
    },
    "dependencies": {
        "formik": "^1.5.2",
        "history": "^4.9.0",
        "react": "^16.8.6",
        "react-dom": "^16.8.6",
        "react-router-dom": "^5.0.0",
        "rxjs": "^6.3.3",
        "yup": "^0.27.0"
    },
    "devDependencies": {
        "@babel/core": "^7.4.3",
        "@babel/preset-env": "^7.4.3",
        "@babel/preset-react": "^7.0.0",
        "babel-loader": "^8.0.5",
        "html-webpack-plugin": "^3.2.0",
        "path": "^0.12.7",
        "webpack": "^4.29.6",
        "webpack-cli": "^3.3.0",
        "webpack-dev-server": "^3.2.1"
    }
}

React Tutorial Webpack Config

Path: /webpack.config.js

Webpack is used to compile and bundle all the project files so they’re ready to be loaded into a browser, it does this with the help of loaders and plugins that are configured in the webpack.config.js file. For more info about webpack check out the webpack docs.

The webpack config file also defines a global config object for the application using the externals property, you can also use this to define different config variables for your development and production environments.

var HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
    mode: 'development',
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader'
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, 'src/'),
        }
    },
    plugins: [new HtmlWebpackPlugin({
        template: './src/index.html'
    })],
    devServer: {
        historyApiFallback: true
    },
    externals: {
        // global app config object
        config: JSON.stringify({
            apiUrl: 'http://localhost:4000'
        })
    }
}

The project is available on GitHub at https://github.com/cornflourblue/react-jwt-authentication-example.

#reactjs #web-development #javascript

What is GEEK

Buddha Community

React (without Redux) - JWT Authentication Tutorial & Example

qwe ewq

1560459569

Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

I Dev

1608261414

React Redux: Token Authentication example with JWT & Axios

In this tutorial, we’re gonna build a React + Redux Application for Token Authentication example with JWT, LocalStorage, React Router, Axios and Bootstrap. I will show you:

  • JWT Authentication Flow for User Signup & User Login
  • Project Structure for React Redux JWT Authentication, LocalStorage, Router, Axios
  • Working with Redux Actions, Reducers, Store for Application state
  • Creating React Components with Form Validation
  • React Components for accessing protected Resources (Authorization)
  • Dynamic Navigation Bar in React App

Inside tutorial, you can also find Spring Boot backend that works well with this React Client:

  • one working with MySQL/PostgreSQL
  • and one working with MongoDB

Overview of React Redux JWT Authentication example

We will build a React application in that:

  • There are Login/Logout, Signup pages.
  • Form data will be validated by front-end before being sent to back-end.
  • Depending on User’s roles (admin, moderator, user), Navigation Bar changes its items automatically.

Here are the screenshots:
– Signup Page:

react-redux-jwt-authentication-token-example-signup

– Signup failed:

react-redux-jwt-authentication-token-example-signup-email-duplicate

– Form Validation Support:

react-redux-jwt-authentication-token-example-form-validation

– Login Page:

react-redux-jwt-authentication-token-example-login

– Profile Page (for successful Login):

react-redux-jwt-authentication-token-example-profile-page

– For Moderator account login, the navigation bar will change by authorities:

react-redux-jwt-authentication-token-example-authorization-login

– Check Browser Local Storage:

react-redux-jwt-authentication-token-example-local-storage

– Check State in Redux using redux-devtools-extension:

react-redux-jwt-authentication-token-example-redux-devtools-extension

User Registration and User Login Flow

For JWT Authentication, we’re gonna call 2 endpoints:

  • POST api/auth/signup for User Registration
  • POST api/auth/signin for User Login

The following flow shows you an overview of Requests and Responses that React Client will make or receive. This React Client must add a JWT to HTTP Header before sending request to protected resources.

react-redux-jwt-authentication-token-example-flow

You can find step by step to implement these back-end servers in following tutorial:

React Component Diagram with Redux, Router, Axios

Let’s look at the diagram below.

react-redux-jwt-authentication-token-example-project-overview

For more details, implementation and Github Source code, please visit:
https://bezkoder.com/react-redux-jwt-auth/

#react #redux #authentication #security #jwt #javascript

How To Set Up Two-Factor Authentication in cPanel

What is 2FA
Two-Factor Authentication (or 2FA as it often referred to) is an extra layer of security that is used to provide users an additional level of protection when securing access to an account.
Employing a 2FA mechanism is a vast improvement in security over the Singe-Factor Authentication method of simply employing a username and password. Using this method, accounts that have 2FA enabled, require the user to enter a one-time passcode that is generated by an external application. The 2FA passcode (usually a six-digit number) is required to be input into the passcode field before access is granted. The 2FA input is usually required directly after the username and password are entered by the client.

#tutorials #2fa #access #account security #authentication #authentication method #authentication token #cli #command line #cpanel #feature manager #google authenticator #one time password #otp #otp authentication #passcode #password #passwords #qr code #security #security code #security policy #security practices #single factor authentication #time-based one-time password #totp #two factor authentication #whm

Reduce Redux Boilerplate Code with Redux-Actions

Redux has become one of the most popular libraries in front-end development since it was introduced by Dan Abramov and Andrew Clark in 2015. They designed it as the successor for Flux, with the support of some developer tools and a few more concepts embedded in it.

Flux is a fancy name for observer pattern further modified to support React. Both Flux and Redux consist of similar concepts like Store, Actions (events in the application). In other words, Flux is a simple JavaScript object but with some middleware like redux-thunk. It can be a function or a promise for Redux. However, Redux is a single source of truth with concepts like immutability, which improve performance. It is one of the main reasons for Redux to dominate in State Management.

Image for post

Flux vs Redux comparison source: enappd.com

Despite its advantages, some developers have found it rather challenging to deal with Redux due to the amount of boilerplate code introduced with it. And the complexity of the code seems to be another reason for the difficulty.

In this article, we will look at how to reduce the boilerplate code brought about by Actions and Reducers using Redux-Actions

#react-redux-boilerplate #react-redux #react #react-actions #redux