Spring Boot Custom Authentication Provider перенаправляет после входа в систему не работает - PullRequest
0 голосов
/ 25 июня 2019

Я реализовал пользовательский провайдер аутентификации в своем приложении 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

Я перебирал этот код и уверен, что мне просто не хватает чего-то маленького, но просто не могу найти проблему.

Спасибо за ваше время.

1 Ответ

0 голосов
/ 27 июня 2019

Спасибо всем ... Что я сделал, чтобы изменить это:

.hasRole("USER").anyRequest().authenticated()

до

.hasRole("USER").anyRequest().authenticated().and().httpBasic()

Это решило мою проблему. Не уверен, что это правильный способ, но, похоже, он работает нормально.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...