Spring Security 如何从FormLoginConfigurer中提取URL?

h9vpoimq  于 2022-11-24  发布在  Spring
关注(0)|答案(1)|浏览(125)

我想访问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的值?

3gtaxfhh

3gtaxfhh1#

你应该在某个地方定义这些URL,你可以在这两个地方使用它们作为参考。它可以在你的application.yml文件中:

security:
  form:
    login-url: "/login"
    login-success-url: "/success"
    other-property: 123

在代码中注入它们(注意类必须是bean):

@Configuration
public class WebSecurityConfig {

  @Value("security.form.login-url")
  private String loginUrl;

  @Value("security.form.login-success-url")
  private String loginSuccessUrl;
  // ...

}

您还可以创建一个ConfigurationProperties来改进代码https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.external-config.typesafe-configuration-properties

相关问题