[英]Spring Security and RequestCache with Anonymous User
那是我的安全配置
@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);
}
问题是当我从/导航到受保护的 URL 时不会调用 CustomRequestCache,因此 SavedRequestAwareAuthenticationSuccessHandler 在登录后不会重定向到请求的页面。
我假设这是因为 permitAll 创建了一个匿名用户。
我必须如何配置 Spring 安全性才能使 SavedRequestAwareAuthenticationSuccessHandler 工作?
作为答案发布,以便我可以包含我的代码。 我尝试重新创建您的设置,这是我的安全配置
@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();
}
}
和我的 controller
@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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.