Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

Explain Authentication In React Application


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

Explain_Authentication_In_React_Application

Table of Content

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

  1. API: API key is a term of authentication through the key and provides access some private data and you have to maintain the key.
  2. CORS(Cross-Origin-Resource-Sharing): is used to limit the HTTP request types and restricted access for resource depend on the domain.
  3. 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<div>You are not authenticated, please click here to authenticate.</div>;
  }
 
  render() {
      return (
        <authenticate oidcsettings="{OidcSettings}" rendernotauthenticated="{this.NotAuthenticated}" userloaded="{this.userLoaded}" userunloaded="{this.userUnLoaded}"><div>If you see this you are authenticated.</div>
        </authenticate>
      )
  }
}
 
export default App;

provide the below properties:

var OidcSettings = {    
  authority: &#39;https://****/identity&#39;,
  client_id: &#39;myclientid&#39;,
  redirect_uri: &#39;https://localhost:9090/&#39;,    
  response_type: &#39;id_token token&#39;,
  scope: &#39;openid profile roles&#39;,
  post_logout_redirect_uri: &#39;https://localhost:9090/&#39;      
};


   

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 &#39;./logo.svg&#39;;
import &#39;./App.css&#39;;

function App() {
  return (<div classname="App"><header classname="App-header">
        <img alt="logo" classname="App-logo" src="{logo}" /><p>
          Edit <code>src/App.js</code> and save to reload.</p>
        <a classname="App-link" href="https://reactjs.org" rel="noopener noreferrer" target="_blank">
          Learn React
        </a></header></div>
  );
}

export default App;


function App() {
  return (<div>
      HEllO MY REACT APP</div>
  );
}

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 &#39;react&#39;;

export default function Dashboard() {
  return(<h2>Dashboard</h2>
  );
}

Save the file

Same code for login component


import React from &#39;react&#39;;

export default function Login() {
  return(<h2>Login page</h2>
  );
}


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 &#39;react&#39;;
import &#39;./App.css&#39;;
import { BrowserRouter, Route, Switch } from &#39;react-router-dom&#39;;
import Dashboard from &#39;../Dashboard/Dashboard&#39;;
import Login from &#39;../Login/Login&#39;;

function App() {
  return (<div classname="wrapper"><h1>Application</h1>
      <browserrouter>
        <switch>
          <route path="/dashboard">
            <dashboard />
          </route>
          <route path="/Login">
            <login />
          </route>
        </switch>
      </browserrouter></div>
  );
}

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 Mobile App Development Company ?

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 &#39;react&#39;;

export default function Login() {
  return(<form>
      <label>
        </label>
<p><label>Username</label></p><label>
        <input type="text" />
      </label>
      <label>
        </label>
<p><label>Password</label></p><label>
        <input type="password" />
      </label>
<div><button type="submit">Submit</button></div></form>
  )
}

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 &#39;react&#39;;
import PropTypes from &#39;prop-types&#39;;
import &#39;./Login.css&#39;;

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

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

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

  return(<div classname="login-wrapper"><h1>Please Log In</h1>
<form onsubmit="{handleSubmit}">
        <label>
          </label>
<p><label>Username</label></p><label>
          <input onchange="{e" type="text" /> setUserName(e.target.value)} /&gt;
        </label>
        <label>
          </label>
<p><label>Password</label></p><label>
          <input onchange="{e" type="password" /> setPassword(e.target.value)} /&gt;
        </label>
<div><button type="submit">Submit</button></div></form></div>
  )
}

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

Explain_Authentication_In_React_Application

Table of Content

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

  1. API: API key is a term of authentication through the key and provides access some private data and you have to maintain the key.
  2. CORS(Cross-Origin-Resource-Sharing): is used to limit the HTTP request types and restricted access for resource depend on the domain.
  3. 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 &#39;react&#39;;
import Authenticate from &#39;react-openidconnect&#39;;
import OidcSettings from &#39;./oidcsettings&#39;;
 
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({ &quot;user&quot;: user });
  } 
  
  userUnLoaded() {
    this.setState({ &quot;user&quot;: undefined });
  } 
 
  NotAuthenticated() {
    return<div>You are not authenticated, please click here to authenticate.</div>;
  }
 
  render() {
      return (
        <authenticate oidcsettings="{OidcSettings}" rendernotauthenticated="{this.NotAuthenticated}" userloaded="{this.userLoaded}" userunloaded="{this.userUnLoaded}"><div>If you see this you are authenticated.</div>
        </authenticate>
      )
  }
}
 
export default App;

provide the below properties:

var OidcSettings = {    
  authority: &#39;https://****/identity&#39;,
  client_id: &#39;myclientid&#39;,
  redirect_uri: &#39;https://localhost:9090/&#39;,    
  response_type: &#39;id_token token&#39;,
  scope: &#39;openid profile roles&#39;,
  post_logout_redirect_uri: &#39;https://localhost:9090/&#39;      
};


   

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 &#39;./logo.svg&#39;;
import &#39;./App.css&#39;;

function App() {
  return (<div classname="App"><header classname="App-header">
        <img alt="logo" classname="App-logo" src="{logo}" /><p>
          Edit <code>src/App.js</code> and save to reload.</p>
        <a classname="App-link" href="https://reactjs.org" rel="noopener noreferrer" target="_blank">
          Learn React
        </a></header></div>
  );
}

export default App;


function App() {
  return (<div>
      HEllO MY REACT APP</div>
  );
}

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 &#39;react&#39;;

export default function Dashboard() {
  return(<h2>Dashboard</h2>
  );
}

Save the file

Same code for login component


import React from &#39;react&#39;;

export default function Login() {
  return(<h2>Login page</h2>
  );
}


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 &#39;react&#39;;
import &#39;./App.css&#39;;
import { BrowserRouter, Route, Switch } from &#39;react-router-dom&#39;;
import Dashboard from &#39;../Dashboard/Dashboard&#39;;
import Login from &#39;../Login/Login&#39;;

function App() {
  return (<div classname="wrapper"><h1>Application</h1>
      <browserrouter>
        <switch>
          <route path="/dashboard">
            <dashboard />
          </route>
          <route path="/Login">
            <login />
          </route>
        </switch>
      </browserrouter></div>
  );
}

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 Mobile App Development Company ?

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 &#39;react&#39;;

export default function Login() {
  return(<form>
      <label>
        </label>
<p><label>Username</label></p><label>
        <input type="text" />
      </label>
      <label>
        </label>
<p><label>Password</label></p><label>
        <input type="password" />
      </label>
<div><button type="submit">Submit</button></div></form>
  )
}

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 &#39;react&#39;;
import PropTypes from &#39;prop-types&#39;;
import &#39;./Login.css&#39;;

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

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

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

  return(<div classname="login-wrapper"><h1>Please Log In</h1>
<form onsubmit="{handleSubmit}">
        <label>
          </label>
<p><label>Username</label></p><label>
          <input onchange="{e" type="text" /> setUserName(e.target.value)} /&gt;
        </label>
        <label>
          </label>
<p><label>Password</label></p><label>
          <input onchange="{e" type="password" /> setPassword(e.target.value)} /&gt;
        </label>
<div><button type="submit">Submit</button></div></form></div>
  )
}

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.