我想访问FormLoginConfigurer设置的URL,特别是想为loginPage、loginProcessingUrl和failureUrl提取URL字符串。这些值配置如下:
public class WebSecurityConfig {
@Bean
public SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeRequests(auth -> auth
.mvcMatchers("/").permitAll()
.mvcMatchers("/**").authenticated())
.formLogin(login -> login
.loginPage("/login")
.loginProcessingUrl("/authenticate")
.failureUrl("/login?error")
.successHandler(new CustomAuthenticationSuccessHandler())
.permitAll())
.build();
}
}
在一个CustomAuthenticationSuccessHandler中,具体在determineTargetUrl方法中,我现在想要根据这些URL做出一些决定。
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
handleRedirect(request, response, authentication);
clearAuthenticationAttributes(request);
}
private void handleRedirect(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(request, authentication);
if (response.isCommitted()) return;
redirectStrategy.sendRedirect(request, response, targetUrl);
}
private String determineTargetUrl(HttpServletRequest request, Authentication authentication) {
Set<String> authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toSet());
SavedRequest savedRequest = (SavedRequest) request.getSession()
.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
if (authorities.contains("ROLE_ADMIN")) return "/admin";
if (authorities.contains("ROLE_USER")) return savedRequest.getRedirectUrl();
throw new IllegalStateException();
}
private void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) return;
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
如何提取loginPage、loginProcessingUrl和failureUrl的值?
1条答案
按热度按时间3gtaxfhh1#
你应该在某个地方定义这些URL,你可以在这两个地方使用它们作为参考。它可以在你的
application.yml
文件中:在代码中注入它们(注意类必须是bean):
您还可以创建一个
ConfigurationProperties
来改进代码https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.external-config.typesafe-configuration-properties