Безопасность Spring и RequestCache с анонимным пользователем - PullRequest
0 голосов
/ 05 мая 2020

Это моя конфигурация безопасности

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .requestCache().requestCache(new CustomRequestCache())
            .and().authorizeRequests()
            .antMatchers("/").permitAll()
            .anyRequest().hasAnyAuthority(Role.getAllRoles())
            .and().formLogin().loginPage(LOGIN_URL).permitAll()
                  .loginProcessingUrl(LOGIN_PROCESSING_URL)
            .failureUrl(LOGIN_FAILURE_URL)
            .successHandler(new SavedRequestAwareAuthenticationSuccessHandler())
            .and().logout().logoutSuccessUrl(LOGOUT_SUCCESS_URL);
}

Проблема в том, что CustomRequestCache не вызывается, когда я перехожу с / на защищенный URL-адрес, и поэтому SavedRequestAwareAuthenticationSuccessHandler не перенаправляет на запрошенную страницу после входа в систему.

Я предполагаю, что это связано с тем, что permissionAll создает анонимного пользователя.

Как мне настроить Spring Security, чтобы SavedRequestAwareAuthenticationSuccessHandler работал?

1 Ответ

1 голос
/ 06 мая 2020

Отправка в качестве ответа, чтобы я мог указать свой код. Я попытался воссоздать вашу настройку, это моя конфигурация безопасности

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String THE_AUTHORITY = "ROLE_ONE";

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password(passwordEncoder().encode("user")).authorities(THE_AUTHORITY);
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable()
                .requestCache().requestCache(new CustomRequestCache())
                .and().authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().hasAnyAuthority(THE_AUTHORITY)
                .and().formLogin().loginPage("/login").permitAll()
                    .loginProcessingUrl("/login")
                    .failureUrl("/")
                .successHandler(new SavedRequestAwareAuthenticationSuccessHandler())
                .and().logout().logoutSuccessUrl("/");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

и мой контроллер

@RestController
public class TestController {

    @GetMapping("/test")
    public String getTest() {
        return "You did it!";
    }

    @GetMapping("/")
    public String getRoot() {
        return "<a href=/test>Go to test</a>";
    }

    @GetMapping("/login")
    public String getLogin() {
        return "<form action=/login method=POST><input name=username /><input name=password /><input type=submit /></form>";
    }
}

Я могу открыть его, перейти к /, щелкнуть ссылку /test в этот момент я перенаправляюсь в форму входа. После входа в систему меня перенаправляют на /test.

Это мой CustomReuqestCache:

public class CustomRequestCache extends HttpSessionRequestCache {
    @Override
    public void saveRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        System.out.println("Saving request to " + httpServletRequest.getRequestURI());
        super.saveRequest(httpServletRequest, httpServletResponse);
    }

    @Override
    public HttpServletRequest getMatchingRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
         System.out.println("Returning request for " + httpServletRequest.getRequestURI());
         return super.getMatchingRequest(httpServletRequest, httpServletResponse);
    }
}
...