Here is the continued article on my previous post for creating a welcome with login and logout using ReactJS. Today’s post explains how to implement login authentication system for your React JS applications. It will show you how to log in with a user and store the user session, so it deals with token-based authentication. Since we are using token-based authentication, it protects if any unauthorized request is made and notices for a new login if required. This makes your application’s authentication to be more secure compared with any other authentication system. Every user details will be stored in an external database and a PHP based API is used in the backend for handling this authentication. Hope you’ll find it more easily using this as your authentication system in your ReactJS projects. Let’s look into the live demo and follow the below code.

Step 2 - Login.js
In constructor function defined the state object for changing input fields. Login() function will communicate with RESTful API and onChange function set the state value based on the user input value.

Final Login.js
Imported Redirect and PostData components. Login function set the state redirtion value to true, one the API is succesful. Based on the state.redirection value, the page will redirect to the home page.

importReact, {Component} from'react';

import {Redirect} from'react-router-dom';

import {PostData} from'../../services/PostData';

import'./Login.css';

class Login extendsComponent {

constructor(){

super();

this.state= {

username:'',

password:'',

redirectToReferrer:false

};

this.login=this.login.bind(this);

this.onChange=this.onChange.bind(this);

}

login() {

if(this.state.username&&this.state.password){

PostData('login',this.state).then((result) => {

let responseJson = result;

if(responseJson.userData){

sessionStorage.setItem('userData',JSON.stringify(responseJson));

this.setState({redirectToReferrer:true});

}

});

}

}

onChange(e){

this.setState({[e.target.name]:e.target.value});

}

render() {

if (this.state.redirectToReferrer||sessionStorage.getItem('userData')){

return (<Redirect to={'/home'}/>)

}

return (

<div className="row" id="Body">

<div className="medium-5 columns left">

<h4>Login</h4>

<label>Username</label>

<input type="text" name="username" onChange={this.onChange}/>

<label>Password</label>

<input type="password" name="password" onChange={this.onChange}/>

<input type="submit" value="Login" onClick={this.login}/>

<a href="/signup">Registration</a>

</div>

</div>

);

}

}

exportdefaultLogin;

PHP
This code contains login ang sigup function with PDO MySQL connetion and it works with Slim framework. Download this project from GitHub.

Hmmmm, your code is just comparing if the tokens match, which to me is not "secure" because anybody can easily get the token value base on the response from the API and use it to submit a JSON data to the API using the token value and exactly the same request headers.