Click here to Skip to main content
15,867,308 members
Articles / Web Development / React

Create user Registration and Login using Web API and React

Rate me:
Please Sign up or sign in to vote.
2.60/5 (3 votes)
8 Nov 2019CPOL2 min read 30.8K   6   2
In this article, we will learn the step by step process of creating login and registration pages using Reactjs and Web API

Introduction

In this article, we will learn the step by step process of creating user registration and login pages usingReactjs and Web API. React is an open-source JavaScript library which is used for creating user interfaces particularly for single page applications. It is used for controlling view layer for web and mobile applications. React was developed by Jordan Walke, a software engineer at Facebook and maintained by Facebook.

Prerequisites

  1. Basic knowledge of React.js and Web API
  2. Visual Studio
  3. Visual Studio Code
  4. SQL Server Management Studio
  5. Node.js

Table of Contents

  • Create a Database and Table
  • Create a Web API Project
  • Create React Project
  • Install Bootstrap and React Strap
  • Add Routing

Create a Database and Table

Open SQL Server Management Studio, create a database named Employees and in this database, create a table. Give that table a name like EmployeeLogin.

SQL
CREATE TABLE [dbo].[EmployeeLogin](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Email] [varchar](50) NULL,
    [Password] [varchar](50) NULL,
    [EmployeeName] [varchar](50) NULL,
    [City] [varchar](50) NULL,
    [Department] [varchar](50) NULL,
 CONSTRAINT [PK_EmployeeLogin] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, _
       IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Create a Web API Project

Open Visual Studio and create a new project.

Image 1

Change the name as LoginApplication and Click OK > Select Web API as its template.

Image 2

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.

Image 3

Click on the "ADO.NET Entity Data Model" option and click "Add". Select EF designer from the database and click the "Next" button.

Image 4

Add the connection properties and select database name on the next page and click OK.

Image 5

Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.

Image 6

Our data model is created successfully now.

Now add a new folder named VM. Right-click on VM folder and add two three classes - Login, Register and Response respectively. Now, paste the following codes in these classes.

Login Class:

C#
public class Login
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

Register and Response Classes:

C#
public class Register
    {
        public int Id { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string EmployeeName { get; set; }
        public string City { get; set; }
        public string Department { get; set; }
    }
C#
public class Response
{
    public string Status { set; get; }
    public string Message { set; get; }
}

Right-click on the Controllers folder and add a new controller. Name it as "Login controller" and add the following namespaces.

C#
using LoginApplication.Models;
using LoginApplication.VM; 

Create two methods in this controller to insert and login, add the following code in this controller.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LoginApplication.Models;
using LoginApplication.VM;

namespace LoginApplication.Controllers
{
    [RoutePrefix("Api/login")]
    public class LoginController : ApiController
    {
        EmployeesEntities DB = new EmployeesEntities();
        [Route("InsertEmployee")]
        [HttpPost]
        public object InsertEmployee(Register Reg)
        {
            try
            {
                EmployeeLogin EL = new EmployeeLogin();
                if (EL.Id == 0)
                {
                    EL.EmployeeName = Reg.EmployeeName;
                    EL.City = Reg.City;
                    EL.Email = Reg.Email;
                    EL.Password = Reg.Password;
                    EL.Department = Reg.Department;
                    DB.EmployeeLogins.Add(EL);
                    DB.SaveChanges();
                    return new Response
                    { Status = "Success", Message = "Record SuccessFully Saved." };
                }
            }
            catch (Exception)
            {

                throw;
            }
            return new Response
            { Status = "Error", Message = "Invalid Data." };
        }
        [Route("Login")]
        [HttpPost]
        public Response employeeLogin(Login login)
        {
            var log = DB.EmployeeLogins.Where(x => x.Email.Equals(login.Email) && 
                      x.Password.Equals(login.Password)).FirstOrDefault();

            if (log == null)
            {
                return new Response { Status = "Invalid", Message = "Invalid User." };
            }
            else
                return new Response { Status = "Success", Message = "Login Successfully" };
        }
    }
}

Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines:

C#
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Create React Project

Now create a new reactjs project by using the following command:

JavaScript
npx create-reatc-app loginapp 

Open the newly created project in Visual Studio code and install reactstrap and bootstrap in this project by using the following command:

Reactjs
npm install --save bootstrap      
npm install --save reactstrap react react-dom

Use the following command to add routing in React:

npm install react-router-dom --save

Now go to src folder and add three new components:

  1. Login.js
  2. Reg.js
  3. Dashboard.js

Now open Reg.js file and add the following code:

JavaScript
import React, { Component } from 'react';
import { Button, Card, CardFooter, CardBody, CardGroup, Col, Container, Form, 
    Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
class Reg extends Component {
  constructor() {
    super();
    this.state = {
      EmployeeName: '',
      City: '',
      Email: '',
      Password: '',
      Department: ''
    }

    this.Email = this.Email.bind(this);
    this.Password = this.Password.bind(this);
    this.EmployeeName = this.EmployeeName.bind(this);
    this.Password = this.Password.bind(this);
    this.Department = this.Department.bind(this);
    this.City = this.City.bind(this);
    this.register = this.register.bind(this);
  }

  Email(event) {
    this.setState({ Email: event.target.value })
  }
 
  Department(event) {
    this.setState({ Department: event.target.value })
  }
 
  Password(event) {
    this.setState({ Password: event.target.value })
  }
  City(event) {
    this.setState({ City: event.target.value })
  }
  EmployeeName(event) {
    this.setState({ EmployeeName: event.target.value })
  }
 
  register(event) {
    fetch('http://localhost:51282/Api/login/InsertEmployee', {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        EmployeeName: this.state.EmployeeName,
        Password: this.state.Password,
        Email: this.state.Email,
        City: this.state.City,
        Department: this.state.Department
      })
    }).then((Response) => Response.json())
      .then((Result) => {
        if (Result.Status == 'Success')
                this.props.history.push("/Dashboard");
        else
          alert('Sorrrrrry !!!! Un-authenticated User !!!!!')
      })
  }
 
  render() {
 
    return (
      <div className="app flex-row align-items-center">
        <Container>
          <Row className="justify-content-center">
            <Col md="9" lg="7" xl="6">
              <Card className="mx-4">
                <CardBody className="p-4">
                  <Form>
                    <div class="row" className="mb-2 pageheading">
                      <div class="col-sm-12 btn btn-primary">
                        Sign Up
                        </div>
                    </div>
                    <InputGroup className="mb-3">
                      <Input type="text"  
                      onChange={this.EmployeeName} placeholder="Enter Employee Name" />
                    </InputGroup>
                    <InputGroup className="mb-3">
                      <Input type="text"  
                      onChange={this.Email} placeholder="Enter Email" />
                    </InputGroup>
                    <InputGroup className="mb-3">
                      <Input type="password"  
                      onChange={this.Password} placeholder="Enter Password" />
                    </InputGroup>
                    <InputGroup className="mb-4">
                      <Input type="text"  
                      onChange={this.City} placeholder="Enter City" />
                    </InputGroup>
                    <InputGroup className="mb-4">
                      <Input type="text"  
                      onChange={this.Department} placeholder="Enter Department" />
                    </InputGroup>
                    <Button  onClick={this.register}  
                    color="success" block>Create Account</Button>
                  </Form>
                </CardBody>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
    );
  }
}

export default Reg;

<container> <row classname="justify-content-center"> 
<card classname="mx-4"> <cardbody classname="p-4">

Now, open the Login.js file, and add the following code:

JavaScript
import React, { Component } from 'react';
import './App.css';
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, 
         InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
class Login extends Component {
    constructor() {
        super();
 
        this.state = {
            Email: '',
            Password: ''
        }
 
        this.Password = this.Password.bind(this);
        this.Email = this.Email.bind(this);
        this.login = this.login.bind(this);
    }
 
    Email(event) {
        this.setState({ Email: event.target.value })
    }
    Password(event) {
        this.setState({ Password: event.target.value })
    }
    login(event) {
        debugger;
        fetch('http://localhost:51282/Api/login/Login', {
            method: 'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                Email: this.state.Email,
                Password: this.state.Password
            })
        }).then((Response) => Response.json())
            .then((result) => {
                console.log(result);
                if (result.Status == 'Invalid')
                    alert('Invalid User');
                else
                    this.props.history.push("/Dashboard");
            })
    }
 
    render() {
        return (
            <div className="app flex-row align-items-center">
                <Container>
                    <Row className="justify-content-center">
                        <Col md="9" lg="7" xl="6">
                            <CardGroup>
                                <Card className="p-2">
                                    <CardBody>
                                        <Form>
                                            <div class="row" 
                                            className="mb-2 pageheading">
                                                <div class="col-sm-12 btn btn-primary">
                                                    Login
                             </div>
                                            </div>
                                            <InputGroup className="mb-3">
                                                <Input type="text" 
                                                 onChange={this.Email} 
                                                 placeholder="Enter Email" />
                                            </InputGroup>
                                            <InputGroup className="mb-4">
                                                <Input type="password" 
                                                onChange={this.Password} 
                                                placeholder="Enter Password" />
                                            </InputGroup>
                                            <Button onClick={this.login} 
                                            color="success" block>Login</Button>
                                        </Form>
                                    </CardBody>
                                </Card>
                            </CardGroup>
                        </Col>
                    </Row>
                </Container>
            </div>
        );
    }
}
 
export default Login;

Open the Dashboard.js file, and add the following code:

JavaScript
import React, { Component } from 'react';
import './App.css';
import { Button, Card, CardBody, CardGroup, Col, Container, Form, 
         Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
  class Dashboard extends Component {
    render() {
 
        return (
            <div class="row" className="mb-2 pageheading">
                <div class="col-sm-12 btn btn-primary">
                    Dashboard 
             </div>
            </div>
        );
    }
}
 
export default Dashboard;

Open the App.css file, and add the following CSS classes:

CSS
text-align: center;      
}      
.navheader{      
  margin-top: 10px;      
  color :black !important;      
  background-color: #b3beca!important      
}    
 
.PageHeading      
{      
  margin-top: 10px;      
  margin-bottom: 10px;      
  color :black !important;      
}

Open the App.js file, and add the following code:

JavaScript
import React from 'react';  
import logo from './logo.svg';  
import './App.css';  
import Login from './Login';  
import Reg from './Reg';  
import Dashboard from './Dashboard';  
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';   
function App() {  
  return (  
    <Router>    
      <div className="container">    
        <nav className="navbar navbar-expand-lg navheader">    
          <div className="collapse navbar-collapse" >    
            <ul className="navbar-nav mr-auto">    
              <li className="nav-item">    
                <Link to={'/Login'} className="nav-link">Login</Link>    
              </li>    
              <li className="nav-item">    
                <Link to={'/Signup'} className="nav-link">Sign Up</Link>    
              </li>      
            </ul>    
          </div>    
        </nav> <br />    
        <Switch>    
          <Route exact path='/Login' component={Login} />    
          <Route path='/Signup' component={Reg} />    
 
        </Switch>    
        <Switch>  
        <Route path='/Dashboard' component={Dashboard} />    
        </Switch>  
      </div>    
    </Router>   
  );  
}  
 
export default App;

Now, run the project by using the npm start command, and check the results.

Checking results

Checking results

Enter the details and click on button.

Enterring details

Entering details

Enter Email and Password and click on login button.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionIs the working code available for download somewhere? Pin
CurtisG3-Mar-20 5:06
professionalCurtisG3-Mar-20 5:06 
QuestionIt login page Pin
Krzysztof Zielonka12-Nov-19 0:46
Krzysztof Zielonka12-Nov-19 0:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.