DEV Community

Cover image for Explain Authentication In React Application
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

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<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: '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/'      
};

Enter fullscreen mode Exit fullscreen mode

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;
}

Enter fullscreen mode Exit fullscreen mode

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 (<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;

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

export default App;

Enter fullscreen mode Exit fullscreen mode

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

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(<h2>Dashboard</h2>
  );
}

Enter fullscreen mode Exit fullscreen mode

Save the file

Same code for login component

import React from 'react';

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

Enter fullscreen mode Exit fullscreen mode

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 (<div classname="wrapper"><h1>Application</h1>
            <browserrouter>
            <switch>
            <route path="/dashboard">
            <dashboard>
          </dashboard></route>
            <route path="/Login">
            <login>
          </login></route>
        </switch>
      </browserrouter></div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

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(<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>
  )
}

Enter fullscreen mode Exit fullscreen mode

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 <login settoken="{setToken}">
  }


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

export default App;
</login>

Enter fullscreen mode Exit fullscreen mode

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'));

Enter fullscreen mode Exit fullscreen mode

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(<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)} />
        </label>
            <label>
          </label>
<p><label>Password</label></p><label>
            <input onchange="{e" type="password"> setPassword(e.target.value)} />
        </label>
<div><button type="submit">Submit</button></div></form></div>
  )
}

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

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)