This is Part 2 of the tutorial on How to a authenticate from React application to Spring Boot API.
In this part you will actually implement user authentication in Spring Boot. Then you will see how to store user credentials in in React using local storage (session or cookies).
We would cover the following:
- Add the LoginRequest Model and Update the User Model
- Write the Authenticate Service Method
- Write the Login Controller Method
- Implement the Registration and RegistrationSuccessful Components
- Implement the Login and LoginSuccessful Components
1. Add the LoginRequest Model and update the User model
The LoginRequest would be used to hold the username and password coming from the request body of a login request. I would just have fields:
- id
- username
- password
We would also add the passwordHash field to the user model and this is going to be a string field
Update the addUser method of the UserService so that when a new user is being saved, the passwordHash field is also set.
2. Write the Authenticate Service Method
Write the authenticate method in the UserService. This method would take a LoginRequest object (username and password) and checks if the values are valid
The authenticate method placed in the UserService and is given below:
public boolean authenticate(String username, String password) { User user = userRepository.findByUsername(username); if (!user.getUsername().equals(username)){ throw new UsernameNotFoundException("User not found in the database"); } if(user.getPasswordHash().equals(bCryptPasswordEncoder.encode(password))) { throw new BadCredentialsException("The password is incorrect"); } return true; }
3. Write the Login Controller Method
You will write the controller method for /login.
This method would receive the LoginRequest in the request body and call the authenticate method. At successful authentication it returns an Ok status code
The login() method is given below:
@PostMapping("/login") public ResponseEntity<String> login(@RequestBody LoginRequest loginRequest, HttpSession session) { try { boolean isAuthenticated = authenticationService.authenticate(loginRequest.getUsername(), loginRequest.getPassword()); if (isAuthenticated) { session.setAttribute("user", loginRequest.getUsername()); return ResponseEntity.ok("Login successful"); } else { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password"); } } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred during login"); } }
Note that this method has HttpSession as its second parameter but you don’t need to worry about it as Spring would handle creating and managing sessions.
4. Implement the Registration and RegistrationSuccessful Components
Create a Registration Component that would contain the following fields:
- firstname
- lastname
- username
- password
- confirmPassword
Get the designed form here.
The markup and script for the RegistrationSuccessful component is given below:
import React from 'react' import {Typography, Container, Box } from '@mui/material'; export default function RegistrationSuccess() { return ( <Container maxWidth="xs"> <Box sx={{ mt: 8, color: 'green' }}> <Typography variant="h3" align="center" gutterBottom> You have successfully Registered. You can now Login </Typography> <Typography variant="h6" align="center" gutterBottom> <a href="#">You can now Login</a> </Typography> </Box> </Container> ) }
5. Create the Login Component
The Login component would contain 2 fields, username and password.
When the user fills and clicks on the Submit, it makes a post request to the /login endpoint and a response of either 200(Ok) or exception is returned.
At successful login, the user should be directed to the LoginSuccess component. You also need to create this component
Get the markup for the Login component here.