VOOZH about

URL: https://dzone.com/articles/create-user-registration-and-login-using-web-api-a

โ‡ฑ Create User Registration and Login Using Web API and ReactJS


Related

  1. DZone
  2. Data Engineering
  3. Databases
  4. Create User Registration and Login Using Web API and ReactJS

Create User Registration and Login Using Web API and ReactJS

Create user registration and login with Web API and React.

By Updated Feb. 03, 20 ยท Tutorial
Likes
Comment
Save
105.2K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction 

ReactJS is one of the major libraries used in building a single-page web application and simple mobile application development. React was developed by Jordan Walke, a software engineer at Facebook; the framework is currently maintained by Facebook. In this article, we will learn how to create user registration and login pages using ReactJS and Web API.

This article covers:

  • Create a database and table
  • Create a Web API Project
  • Create React Project
  • Install Bootstrap and React strap
  • Add Routing

Prerequisites 

  • Basic knowledge of React.js and Web API
  • Visual Studio
  • Visual Studio Code
  • SQL Server Management Studio
  • Node.js
You may also like:  CRUD Operations Using ReactJS and ASP.NET Web API

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




xxxxxxxxxx
1
14


1
CREATE TABLE [dbo].[EmployeeLogin](    
2
   [Id] [int] IDENTITY(1,1) NOT NULL,    
3
   [Email] [varchar](50) NULL,    
4
   [Password] [varchar](50) NULL,    
5
   [EmployeeName] [varchar](50) NULL,    
6
   [City] [varchar](50) NULL,    
7
   [Department] [varchar](50) NULL,    
8
 CONSTRAINT [PK_EmployeeLogin] PRIMARY KEY CLUSTERED     
9
(    
10
   [Id] ASC    
11
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
12
) ON [PRIMARY]    
13
 
 
14
GO 



Create a Web API Project

Open Visual Studio and create a new project.

Creating a new project


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

Selecting Web API template


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

Adding new item


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

Adding entity data model


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

Selecting database name


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

Adding image title


Now, our data model is successfully created.

Next, we add a new folder named "VM." Right-click on it and add three classes โ€” Login, Register, and Response. Now, paste the following code in these classes.

Login Class

Java




xxxxxxxxxx
1


1
 public class Login
2
   {
3
        public string Email { get; set; }
4
        public string Password { get; set; }
5
   }



Register Class

Java




xxxxxxxxxx
1


1
 public class Register
2
   {
3
        public int Id { get; set; }
4
        public string Email { get; set; }
5
        public string Password { get; set; }
6
        public string EmployeeName { get; set; }
7
        public string City { get; set; }
8
        public string Department { get; set; }
9
   }



Response Class

Java




xxxxxxxxxx
1


1
 public class Response
2
   {
3
        public string Status { set; get; }
4
        public string Message { set; get; }
5
 
 
6
   }



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

Java




xxxxxxxxxx
1


1
using LoginApplication.Models;
2
using LoginApplication.VM;



Create two methods in this controller to insert and log in. Add the following code in this controller:

Java




xxxxxxxxxx
1
59


1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Net;
5
using System.Net.Http;
6
using System.Web.Http;
7
using LoginApplication.Models;
8
using LoginApplication.VM;
9
 
 
10
namespace LoginApplication.Controllers
11
{
12
   [RoutePrefix("Api/login")]
13
    public class LoginController : ApiController
14
   {
15
        EmployeesEntities DB = new EmployeesEntities();
16
       [Route("InsertEmployee")]
17
       [HttpPost]
18
        public object InsertEmployee(Register Reg)
19
       {
20
            try
21
           {
22
 
 
23
                EmployeeLogin EL = new EmployeeLogin();
24
                if (EL.Id == 0)
25
               {
26
                    EL.EmployeeName = Reg.EmployeeName;
27
                    EL.City = Reg.City;
28
                    EL.Email = Reg.Email;
29
                    EL.Password = Reg.Password;
30
                    EL.Department = Reg.Department;
31
                    DB.EmployeeLogins.Add(EL);
32
                    DB.SaveChanges();
33
                    return new Response
34
                   { Status = "Success", Message = "Record SuccessFully Saved." };
35
               }
36
           }
37
            catch (Exception)
38
           {
39
 
 
40
                throw;
41
           }
42
            return new Response
43
           { Status = "Error", Message = "Invalid Data." };
44
       }
45
       [Route("Login")]
46
       [HttpPost]
47
        public Response employeeLogin(Login login)
48
       {
49
            var log = DB.EmployeeLogins.Where(x => x.Email.Equals(login.Email) && x.Password.Equals(login.Password)).FirstOrDefault();
50
 
 
51
            if (log == null)
52
           {
53
                return new Response { Status = "Invalid", Message = "Invalid User." };
54
           }
55
            else
56
                return new Response { Status = "Success", Message = "Login Successfully" };
57
       }
58
   }
59
}



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:

Java




xxxxxxxxxx
1


1
  EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
2
  config.EnableCors(cors);



Create the React Project

Now, create a new ReactJS project by using the following command.

Java




xxxxxxxxxx
1


1
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.

Java




xxxxxxxxxx
1


1
npm install --save bootstrap      
2
npm install --save reactstrap react react-dom  



Use the following command to add routing in React.

Java




xxxxxxxxxx
1


1
npm install react-router-dom --save  



Now, go to the src folder and add three new components.

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

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

Java




xxxxxxxxxx
1
115


1
import React, { Component } from 'react';
2
import { Button, Card, CardFooter, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
3
 
 
4
class Reg extends Component {
5
 
 
6
  constructor() {
7
    super();
8
 
 
9
    this.state = {
10
      EmployeeName: '',
11
      City: '',
12
      Email: '',
13
      Password: '',
14
      Department: ''
15
   }
16
 
 
17
 
 
18
    this.Email = this.Email.bind(this);
19
    this.Password = this.Password.bind(this);
20
    this.EmployeeName = this.EmployeeName.bind(this);
21
    this.Password = this.Password.bind(this);
22
    this.Department = this.Department.bind(this);
23
    this.City = this.City.bind(this);
24
    this.register = this.register.bind(this);
25
 }
26
 
 
27
 
 
28
 
 
29
  Email(event) {
30
    this.setState({ Email: event.target.value })
31
 }
32
 
 
33
  Department(event) {
34
    this.setState({ Department: event.target.value })
35
 }
36
 
 
37
  Password(event) {
38
    this.setState({ Password: event.target.value })
39
 }
40
  City(event) {
41
    this.setState({ City: event.target.value })
42
 }
43
  EmployeeName(event) {
44
    this.setState({ EmployeeName: event.target.value })
45
 }
46
 
 
47
  register(event) {
48
 
 
49
    fetch('http://localhost:51282/Api/login/InsertEmployee', {
50
      method: 'post',
51
      headers: {
52
        'Accept': 'application/json',
53
        'Content-Type': 'application/json'
54
     },
55
      body: JSON.stringify({
56
 
 
57
 
 
58
        EmployeeName: this.state.EmployeeName,
59
        Password: this.state.Password,
60
        Email: this.state.Email,
61
        City: this.state.City,
62
        Department: this.state.Department
63
     })
64
   }).then((Response) => Response.json())
65
     .then((Result) => {
66
        if (Result.Status == 'Success')
67
                this.props.history.push("/Dashboard");
68
        else
69
          alert('Sorrrrrry !!!! Un-authenticated User !!!!!')
70
     })
71
 }
72
 
 
73
  render() {
74
 
 
75
    return (
76
      <div className="app flex-row align-items-center">
77
        <Container>
78
          <Row className="justify-content-center">
79
            <Col md="9" lg="7" xl="6">
80
              <Card className="mx-4">
81
                <CardBody className="p-4">
82
                  <Form>
83
                    <div class="row" className="mb-2 pageheading">
84
                      <div class="col-sm-12 btn btn-primary">
85
                        Sign Up
86
                        </div>
87
                    </div>
88
                    <InputGroup className="mb-3">
89
                      <Input type="text"  onChange={this.EmployeeName} placeholder="Enter Employee Name" />
90
                    </InputGroup>
91
                    <InputGroup className="mb-3">
92
                      <Input type="text"  onChange={this.Email} placeholder="Enter Email" />
93
                    </InputGroup>
94
                    <InputGroup className="mb-3">
95
                      <Input type="password"  onChange={this.Password} placeholder="Enter Password" />
96
                    </InputGroup>
97
                    <InputGroup className="mb-4">
98
                      <Input type="text"  onChange={this.City} placeholder="Enter City" />
99
                    </InputGroup>
100
                    <InputGroup className="mb-4">
101
                      <Input type="text"  onChange={this.Department} placeholder="Enter Department" />
102
                    </InputGroup>
103
                    <Button  onClick={this.register}  color="success" block>Create Account</Button>
104
                  </Form>
105
                </CardBody>
106
              </Card>
107
            </Col>
108
          </Row>
109
        </Container>
110
      </div>
111
   );
112
 }
113
}
114
 
 
115
export default Reg;



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

Java




xxxxxxxxxx
1
84


1
import React, { Component } from 'react';
2
import './App.css';
3
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
4
class Login extends Component {
5
    constructor() {
6
        super();
7
 
 
8
        this.state = {
9
            Email: '',
10
            Password: ''
11
       }
12
 
 
13
        this.Password = this.Password.bind(this);
14
        this.Email = this.Email.bind(this);
15
        this.login = this.login.bind(this);
16
   }
17
 
 
18
    Email(event) {
19
        this.setState({ Email: event.target.value })
20
   }
21
    Password(event) {
22
        this.setState({ Password: event.target.value })
23
   }
24
    login(event) {
25
        debugger;
26
        fetch('http://localhost:51282/Api/login/Login', {
27
            method: 'post',
28
            headers: {
29
                'Accept': 'application/json',
30
                'Content-Type': 'application/json'
31
           },
32
            body: JSON.stringify({
33
                Email: this.state.Email,
34
                Password: this.state.Password
35
           })
36
       }).then((Response) => Response.json())
37
           .then((result) => {
38
                console.log(result);
39
                if (result.Status == 'Invalid')
40
                    alert('Invalid User');
41
                else
42
                    this.props.history.push("/Dashboard");
43
           })
44
   }
45
 
 
46
    render() {
47
 
 
48
        return (
49
            <div className="app flex-row align-items-center">
50
                <Container>
51
                    <Row className="justify-content-center">
52
                        <Col md="9" lg="7" xl="6">
53
 
 
54
                            <CardGroup>
55
                                <Card className="p-2">
56
                                    <CardBody>
57
                                        <Form>
58
                                            <div class="row" className="mb-2 pageheading">
59
                                                <div class="col-sm-12 btn btn-primary">
60
                                                    Login
61
                             </div>
62
                                            </div>
63
                                            <InputGroup className="mb-3">
64
 
 
65
                                                <Input type="text" onChange={this.Email} placeholder="Enter Email" />
66
                                            </InputGroup>
67
                                            <InputGroup className="mb-4">
68
 
 
69
                                                <Input type="password" onChange={this.Password} placeholder="Enter Password" />
70
                                            </InputGroup>
71
                                            <Button onClick={this.login} color="success" block>Login</Button>
72
                                        </Form>
73
                                    </CardBody>
74
                                </Card>
75
                            </CardGroup>
76
                        </Col>
77
                    </Row>
78
                </Container>
79
            </div>
80
       );
81
   }
82
}
83
 
 
84
export default Login;



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

Java




xxxxxxxxxx
1
17


1
import React, { Component } from 'react';
2
import './App.css';
3
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
4
  class Dashboard extends Component {
5
    render() {
6
 
 
7
        return (
8
            <div class="row" className="mb-2 pageheading">
9
                <div class="col-sm-12 btn btn-primary">
10
                    Dashboard 
11
             </div>
12
            </div>
13
       );
14
   }
15
}
16
 
 
17
export default Dashboard;



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

Java




xxxxxxxxxx
1
15


1
.App {      
2
  text-align: center;      
3
}      
4
.navheader{      
5
  margin-top: 10px;      
6
  color :black !important;      
7
  background-color: #b3beca!important      
8
}    
9
 
 
10
.PageHeading      
11
{      
12
  margin-top: 10px;      
13
  margin-bottom: 10px;      
14
  color :black !important;      
15
} 



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

Java




xxxxxxxxxx
1
38


1
import React from 'react';  
2
import logo from './logo.svg';  
3
import './App.css';  
4
import Login from './Login';  
5
import Reg from './Reg';  
6
import Dashboard from './Dashboard';  
7
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';   
8
function App() {  
9
  return (  
10
    <Router>    
11
      <div className="container">    
12
        <nav className="navbar navbar-expand-lg navheader">    
13
          <div className="collapse navbar-collapse" >    
14
            <ul className="navbar-nav mr-auto">    
15
              <li className="nav-item">    
16
                <Link to={'/Login'} className="nav-link">Login</Link>    
17
              </li>    
18
              <li className="nav-item">    
19
                <Link to={'/Signup'} className="nav-link">Sign Up</Link>    
20
              </li>    
21
 
 
22
            </ul>    
23
          </div>    
24
        </nav> <br />    
25
        <Switch>    
26
          <Route exact path='/Login' component={Login} />    
27
          <Route path='/Signup' component={Reg} />    
28
 
 
29
        </Switch>    
30
        <Switch>  
31
        <Route path='/Dashboard' component={Dashboard} />    
32
        </Switch>  
33
      </div>    
34
    </Router>   
35
 );  
36
}  
37
 
 
38
export default App;



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

Checking results


Enter the details and click on the create an account button:

Entering details


Enter Email and Password and click on the login button.

Further Reading

Consuming REST APIs With React.js

Web API Database Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Prototype for a Java Database Application With REST and Security
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Handling Embedded Data in NoSQL With Java

Partner Resources

ร—

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: