'Endpoint for user login (Spring Security)
Trying to write endpoint / login to login user (I'm using Spring Security). After logging in, the user would have access to change his password, etc. The only problem is that when he tries to use, for example, the aforementioned endpoint to change the password, he gets an unauthorized error.
@PostMapping("/login")
void login(@RequestBody LoginDTO dto) {
var token = authenticationProvider.authenticate(new
UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword()));
}
public class CustomAuthenticationProvider implements AuthenticationProvider {
private final UserDetailsService userDetailsService;
private final PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws
AuthenticationException {
var authUserName = authentication.getName();
log.info("Auth user name: {}", authUserName);
var authPassword = authentication.getCredentials().toString();
log.info("Auth password:{}", authPassword);
var loadedUser = userDetailsService.loadUserByUsername(authUserName);
if (loadedUser == null) {
throw new UsernameNotFoundException(authUserName);
}
var isAuthPasswordCorrect = passwordEncoder.matches(authPassword, loadedUser.getPassword());
log.info("Is auth password correct: {}", isAuthPasswordCorrect);
if (!isAuthPasswordCorrect) {
throw new BadCredentialsException(authPassword);
}
if (!loadedUser.isAccountNonLocked()) {
throw new LockedException(loadedUser.getUsername());
}
return new UsernamePasswordAuthenticationToken(
authUserName, authPassword, loadedUser.getAuthorities());
}
@Override
public boolean supports(Class<?> aClass) {
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] endpointsForAll = {
"/registration", "/login", "/task-manager-openapi/**", "/swagger-ui/**"
};
private final AuthenticationProvider authenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers(endpointsForAll).permitAll()
.mvcMatchers(HttpMethod.GET, "/users").hasAnyAuthority("ADMIN")
.mvcMatchers(HttpMethod.PATCH, "/users/{username}/status").hasAnyAuthority("ADMIN")
.antMatchers("/h2/console/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.headers().frameOptions().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
}
I don't know where to pass this token next.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
