Reputation: 1522
I am very new to spring security. I am trying to implement JWT
filters in my web application to make it stateless. I have piece of code, when users hits the /login
path, the control goes to the method,
public LoginResponse login(
AuthenticationRequest authenticationRequest, Device device )
throws WebappException
{
// Perform the security
final Authentication authentication = authenticationManager
.authenticate(new
UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(),
authenticationRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
/** some more logic**/
Here I am not understanding the purpose of
final Authentication authentication = authenticationManager
.authenticate(new
UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(),
authenticationRequest.getPassword()));
Please guide me!
AuthenticationRequest
has two fields userName
and password
.
Upvotes: 0
Views: 1380
Reputation: 786
The authenticationManager.authenticate()
method passes the UsernamePasswordAuthenticationToken
to the AuthenticationProvider
and tries to authenticate to user with provided username and password.
Authentication
object with granted authorities if successful,You can then call authentication.isAuthenticated()
to know if the token has been authenticated.
If you want to access a database to check authentication, you should use the DaoAuthenticationProvider
implementation (or AbstractUserDetailsAuthenticationProvider
).
It retrieves user details from the interface UserDetailsService
. So you need to create a class MyUserDetailsService
which implements UserDetailsService
overriding the loadUserByUsername(String username)
method and returning UserDetails
.
UserDetails
contains username, password, authorities. Create your own MyUserdetails
class wich implements UserDetails
interface.
Then, configure Spring to reference your cutom class:
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService);
More details on http://www.baeldung.com/spring-security-authentication-with-a-database
Or you can also use the JdbcUserDetailsManagerConfigurer to directly specify you datasource and SQL queries:
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, role from user_roles where username=?");
}
Regarding JWT, I think your login method checks at first the authentication of a user and then should build a JWT with the user details and return it to the browser. Then the client can resend this token to the server and this JWT will be decrypted and validated by another method. More information on https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java
Upvotes: 1