×

iFour Logo

Explain Authentication In React Application

Kapil Panchal - July 06, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Explain Authentication In React Application

Introduction


Today, we can easily get all details from internet and store the all details in a server, therefore, if we don’t get any security then there would be high chance to lost information or Unauthorized system to modify or steal the data. Authentication is the process to manage the program structure, user has the right privileges to access the particular page to which the user has privileges.

What is the Authentication?


An Authentication is a process of check a valid user or not. Check the real identity of each user, it is process is the Act of confirming something that it claims to be. For example login criteria.

React API Authentication & Authorization


Methods:

API key that allows user for particular services.

When you get API services in a limited number of domains and strict API.

Enacting a CORS Policy would provide future protection because it is restricted access to some authorized entities.

Limitation of IP WhiteListing:

Static IP address: Address doesn’t change

Dynamic IP address: Address can be change

  • API: API key is a term of authentication through the key and provides access some private data and you have to maintain the key.

  • CORS(Cross-Origin-Resource-Sharing): is used to limit the HTTP request types and restricted access for resource depend on the domain.

  • IP WhiteListing: When you have to grant a network and you have a limited number of IP addresses, each approved user shares their home IP addresses with the network administrator. When they enter the IP address the IP whitelisting that grant network access

Ways of Implementing API Authorization and Authentication


OAuth: is a process of a way to provide services to access other resources.

For example when you signup for your Github account. Commonly show in a screen as Sign up with Github or Signup with Facebook and you can directly login with Facebook

That means you do not need to required username or password for the login you authorized to access your information

OAuth is implemented behind authentication services.

How to work OAuth: one service offers the user to integrate with another service. If accepted, the service sends user information to another service and asks has any user registered with this email. It has a user with the same email and they have implemented OAuth.

We can assume that this authorization request is valid.

OpenID Connect: this allows the client to verify the identity of the end-user.

npm install --save react-OpenID connect

Create React Application example



import React, { Component } from 'react';
import Authenticate from 'react-openidconnect';
import OidcSettings from './oidcsettings';
 
class App extends Component {
 
  constructor(props) {
    super(props);
    this.userLoaded = this.userLoaded.bind(this); 
    this.userUnLoaded = this.userUnLoaded.bind(this);
 
    this.state = { user: undefined };
  }  
 
  userLoaded(user) {
    if (user)
      this.setState({ "user": user });
  } 
  
  userUnLoaded() {
    this.setState({ "user": undefined });
  } 
 
  NotAuthenticated() {
    return
You are not authenticated, please click here to authenticate.
; } render() { return (
If you see this you are authenticated.
) } } export default App; provide the below properties: var OidcSettings = { authority: 'https://****/identity', client_id: 'myclientid', redirect_uri: 'https://localhost:9090/', response_type: 'id_token token', scope: 'openid profile roles', post_logout_redirect_uri: 'https://localhost:9090/' };

Login Authentication in React


Mandatory: first you have to development environment running Node.js recommend version 10.22.0 and npm version 6.14.6 you have to install this on mac OS

Follow the steps:

First you have to create react project

Check npm run successfully or not

Node -ve

if you see the version name that means your node installed successfully

npx create-react-app project_name

cd project_name

npm start

if you want to provide some style so you can add manually css in app.css file

Mycss.css

App-header {
  background-color: gray;
  padding: 10px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}
			   

Every time you have to add the packages as per your project requirement

When your project run successfully on the localhost

Open the App.js file


import logo from './logo.svg';
import './App.css';

function App() {
  return (
logo

Edit src/App.js and save to reload.

Learn React
); } export default App;

function App() {
  return (
HEllO MY REACT APP
); } export default App;

Now create a login page

you have to install the package

$ npm install react-router-dom

After installing the package you see the output like that

+ arereact-router-dom@5.2.0

added 13 packages, and audited 1974 packages in 6s

you have to create two components called which is act as private, user cant access the page until they log in successfully.

Create directory

mkdir src/components/Dashboard

mkdir src/components/Login


import React from 'react';

export default function Dashboard() {
  return(

Dashboard

); }

Save the file

Same code for login component


import React from 'react';

export default function Login() {
  return(

Login page

); }

Open App.css file and import both component

import React from 'react';
import './App.css';
import Dashboard from '../Dashboard/Dashboard';
import Login from '../Login/Login';

function App() {
  return (
    <>
  );
}

export default App;
				

now you have to import Route,Switch BrowserRoute

npm install react-router-dom:



import React from 'react';
import './App.css';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Dashboard from '../Dashboard/Dashboard';
import Login from '../Login/Login';

function App() {
  return (

Application

); } export default App;

if you run the project http://localhost:3001/dashboard

you can see the dashboard page but still, there is no security, dashboard page show after successful login for the security we have to render the page.

Planning to Hire React Developers from dedicated team? Your Search ends here.

Follow the steps :

We have to create a new directory for the login component

mkdir src/component /login_success

Open login page directory in a text editor

Create a login form


import React from 'react';

export default function Login() {
  return(

) }

Open the App.js file

import React, { useState } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import './App.css';
import Dashboard from '../Dashboard/Dashboard';
import LoginPage from '../Loginpage/Loginpage';
import Login from '../Login/Login';



function App() {
  const [token, setToken] = useState();
  if(!token) {
    return 
  }


  return (

Application

); } export default App;

Have you try to run the project you can still visit the dashboard page that means the token has not yet been set

now you have to call the local API from your login page and render the component after you successfully retrieve the token.

npm install --save-dev express cors

you have to open a new file called server.js but remember that do not add this file to the src/ directory

$ nano server.js

Import express in the server.js

const express = require('express');
const cors = require('cors')
const app = express();

app.use(cors());

app.use('/login', (req, res) => {
  res.send({
    token: 'test123'
  });
});
app.listen(8080, () => console.log('API is running on http://localhost:8080/login'));
				

you have to set the tokens and set the props as per above the code


import React, { useState } from 'react';
import PropTypes from 'prop-types';
import './Login.css';

async function loginUser(credentials) {
 return fetch('http://localhost:8080/login', {
   method: 'POST',
   headers: {
     'Content-Type': 'application/json'
   },
   body: JSON.stringify(credentials)
 })
   .then(data => data.json())
}

export default function Login({ setToken }) {
  const [username, setUserName] = useState();
  const [password, setPassword] = useState();

  const handleSubmit = async e => {
    e.preventDefault();
    const token = await loginUser({
      username,
      password
    });
    setToken(token);
  }

  return(

Please Log In

) } Login.propTypes = { setToken: PropTypes.func.isRequired };

When you run the project you will create a successful login

Conclusion


Authentication is an indispensable requirement for many applications. Authentication is all about security concern. But if you focus on the validate data passing rendering of data entity at the right time, it becomes a lightweight process.

Explain Authentication In React Application Table of Content 1. Introduction 2. What is the Authentication? 3. React API Authentication & Authorization 4. Ways of Implementing API Authorization and Authentication 5. Create React Application example 6. Login Authentication in React 7. Conclusion Introduction Today, we can easily get all details from internet and store the all details in a server, therefore, if we don’t get any security then there would be high chance to lost information or Unauthorized system to modify or steal the data. Authentication is the process to manage the program structure, user has the right privileges to access the particular page to which the user has privileges. What is the Authentication? An Authentication is a process of check a valid user or not. Check the real identity of each user, it is process is the Act of confirming something that it claims to be. For example login criteria. React API Authentication & Authorization Methods: API key that allows user for particular services. When you get API services in a limited number of domains and strict API. Enacting a CORS Policy would provide future protection because it is restricted access to some authorized entities. Limitation of IP WhiteListing: Static IP address: Address doesn’t change Dynamic IP address: Address can be change API: API key is a term of authentication through the key and provides access some private data and you have to maintain the key. CORS(Cross-Origin-Resource-Sharing): is used to limit the HTTP request types and restricted access for resource depend on the domain. IP WhiteListing: When you have to grant a network and you have a limited number of IP addresses, each approved user shares their home IP addresses with the network administrator. When they enter the IP address the IP whitelisting that grant network access Ways of Implementing API Authorization and Authentication OAuth: is a process of a way to provide services to access other resources. For example when you signup for your Github account. Commonly show in a screen as Sign up with Github or Signup with Facebook and you can directly login with Facebook That means you do not need to required username or password for the login you authorized to access your information OAuth is implemented behind authentication services. How to work OAuth: one service offers the user to integrate with another service. If accepted, the service sends user information to another service and asks has any user registered with this email. It has a user with the same email and they have implemented OAuth. We can assume that this authorization request is valid. OpenID Connect: this allows the client to verify the identity of the end-user. npm install --save react-OpenID connect Create React Application example import React, { Component } from 'react'; import Authenticate from 'react-openidconnect'; import OidcSettings from './oidcsettings'; class App extends Component { constructor(props) { super(props); this.userLoaded = this.userLoaded.bind(this); this.userUnLoaded = this.userUnLoaded.bind(this); this.state = { user: undefined }; } userLoaded(user) { if (user) this.setState({ "user": user }); } userUnLoaded() { this.setState({ "user": undefined }); } NotAuthenticated() { returnYou are not authenticated, please click here to authenticate.; } render() { return ( If you see this you are authenticated. ) } } export default App; provide the below properties: var OidcSettings = { authority: 'https://****/identity', client_id: 'myclientid', redirect_uri: 'https://localhost:9090/', response_type: 'id_token token', scope: 'openid profile roles', post_logout_redirect_uri: 'https://localhost:9090/' }; Read More: App Store Optimization For Mobile Platforms Login Authentication in React Mandatory: first you have to development environment running Node.js recommend version 10.22.0 and npm version 6.14.6 you have to install this on mac OS Follow the steps: First you have to create react project Check npm run successfully or not Node -ve if you see the version name that means your node installed successfully npx create-react-app project_name cd project_name npm start if you want to provide some style so you can add manually css in app.css file Mycss.css App-header { background-color: gray; padding: 10px; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } Every time you have to add the packages as per your project requirement When your project run successfully on the localhost Open the App.js file import logo from './logo.svg'; import './App.css'; function App() { return ( Edit src/App.js and save to reload. Learn React ); } export default App; function App() { return ( HEllO MY REACT APP ); } export default App; Now create a login page you have to install the package $ npm install react-router-dom After installing the package you see the output like that + arereact-router-dom@5.2.0 added 13 packages, and audited 1974 packages in 6s you have to create two components called which is act as private, user cant access the page until they log in successfully. Create directory mkdir src/components/Dashboard mkdir src/components/Login import React from 'react'; export default function Dashboard() { return(Dashboard ); } Save the file Same code for login component import React from 'react'; export default function Login() { return(Login page ); } Open App.css file and import both component import React from 'react'; import './App.css'; import Dashboard from '../Dashboard/Dashboard'; import Login from '../Login/Login'; function App() { return ( ); } export default App; now you have to import Route,Switch BrowserRoute npm install react-router-dom: import React from 'react'; import './App.css'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import Dashboard from '../Dashboard/Dashboard'; import Login from '../Login/Login'; function App() { return (Application ); } export default App; if you run the project http://localhost:3001/dashboard you can see the dashboard page but still, there is no security, dashboard page show after successful login for the security we have to render the page. Planning to Hire React Developers from dedicated team? Your Search ends here. See here Follow the steps : We have to create a new directory for the login component mkdir src/component /login_success Open login page directory in a text editor Create a login form import React from 'react'; export default function Login() { return( Username Password Submit ) } Open the App.js file import React, { useState } from 'react'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import './App.css'; import Dashboard from '../Dashboard/Dashboard'; import LoginPage from '../Loginpage/Loginpage'; import Login from '../Login/Login'; function App() { const [token, setToken] = useState(); if(!token) { return } return (Application ); } export default App; Have you try to run the project you can still visit the dashboard page that means the token has not yet been set now you have to call the local API from your login page and render the component after you successfully retrieve the token. npm install --save-dev express cors you have to open a new file called server.js but remember that do not add this file to the src/ directory $ nano server.js Import express in the server.js const express = require('express'); const cors = require('cors') const app = express(); app.use(cors()); app.use('/login', (req, res) => { res.send({ token: 'test123' }); }); app.listen(8080, () => console.log('API is running on http://localhost:8080/login')); you have to set the tokens and set the props as per above the code import React, { useState } from 'react'; import PropTypes from 'prop-types'; import './Login.css'; async function loginUser(credentials) { return fetch('http://localhost:8080/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(credentials) }) .then(data => data.json()) } export default function Login({ setToken }) { const [username, setUserName] = useState(); const [password, setPassword] = useState(); const handleSubmit = async e => { e.preventDefault(); const token = await loginUser({ username, password }); setToken(token); } return(Please Log In Username setUserName(e.target.value)} /> Password setPassword(e.target.value)} /> Submit ) } Login.propTypes = { setToken: PropTypes.func.isRequired }; When you run the project you will create a successful login Conclusion Authentication is an indispensable requirement for many applications. Authentication is all about security concern. But if you focus on the validate data passing rendering of data entity at the right time, it becomes a lightweight process.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
10 Executive Dashboard Examples for Consultants and CEOs
10 Executive Dashboard Examples for Consultants and CEOs

There is a principle behind every business. “If you don’t keep track of essentials, you won’t get clear direction, eventually causing your company to stumble.” To manage this scenario,...

How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...