Я реализовал пользовательский провайдер аутентификации в своем приложении Spring Boot. Это делается для аутентификации пользователей в сторонней системе, и в случае успеха я перенаправлю их на страницу / user.
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.
.
.
private String privateResources[] = new String[]{"/user/**"};
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(publicResources).permitAll()
.antMatchers(privateResources).hasRole("USER").anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.failureUrl("/login?error=true")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(secureAuthenticationSuccessHandler)
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this.customAuthenticationProvider);
}
Ниже приведена часть моего пользовательского поставщика аутентификации.
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
ResponseEntity responseEntity = postAuthRequest(name, password);
if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new UsernamePasswordAuthenticationToken(name, password, grantedAuthorities);
} else {
throw new BadCredentialsException(responseEntity.getStatusCode().toString());
}
}
Тогда в моем SecureAuthenticationSuccessHandler у меня есть:
public class SecureAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = "/user";
redirectStrategy.sendRedirect(request, response, targetUrl);
}
Аутентификация работает, и я получаю статус OK от CustomAuthenticationProvider.
Но когда происходит перенаправление на / user, пружина возвращает:
Пользователь 'myuser' попытался получить доступ к защищенному URL: / user
Я перебирал этот код и уверен, что мне просто не хватает чего-то маленького, но просто не могу найти проблему.
Спасибо за ваше время.