How to handle Login authentication in Spring

In this article, you are going to learn how to use Spring Security to achieve a login authentication functionality.
spring-featured-image
The login page represents a form which asks for details such as username and password. That same login page can be done in Angular and the authentication process itself will be performed by Spring Security.

There is a token which is grabbed from the server and then is sent back to the client. In addition, the server expects the same token for evevy signle request onwards.

Workflow

When the user submits a login form, as mentioned above, he has to enter username and password (most often). When he submits the form, there is an API call which comes from Spring Web. The path might look like /login and is invoked through HTTP POST method.

You could write the Authentication logic in the front end, for example in Angular. But in this article, we are going to write it on the server-side, a.k.a. Spring. There are a couple of ways we can do accomplish our objective. One is by writing a controller class and the other one is by extending UsernamePasswordAuthenticationFilter. We are going to use the first way – by creating a login method that authenticates the user and returns true or false.

ControllerClass.java

// the POST method
@PostMapping(value="/login")
public boolean login(@RequsetBody Employee reqEmployee, HttpServletRequest request) {
	Authentication auth = null;
	UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(reqEmployee.getUsername(), reqEmployee.getPassword());
	
	try {
		auth = authenticationProvider.authenticate(token);
		SecurityContextHolder.getContext().setAuthentication(auth);
		Employee employee = (Employee) authentication.getPrincipal();
		employee.setPassword(null);
		return true;
	}
	catch (BadCredentialsException exception) {
		// you can also log the exception message, for example using Logger
		return false;
	}
}

That’s a simple POST method that returns true or false depending upon whether the user has successfully been authenticated or not.




Breakdown

First we create auth to act as an Authentication instance and at first we make it null. Then we generate an Authentication token for the username and the password the user entered. Then we have a tray {} catch() {} block which tries to authenticate the user based on the token and if everything is successful, returns true. Catch on the other hand, is run if the authentication didn’t go through and returns false.

And again, this method should be in a Controller class.

3 1 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments