java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringSecurity过滤器链

SpringSecurity的安全过滤器链功能详解

作者:康小庄

本文介绍了如何配置SpringSecurity的安全过滤器链,包括定义URL路径的访问权限、用户认证和授权配置、自定义CSRF过滤器等内容,通过这些配置,可以实现对不同URL路径的访问控制以及用户的登录、注销等功能,感兴趣的朋友一起看看吧

主要是用于配置Spring Security的安全过滤器链(SecurityFilterChain),以及定义用户认证和授权的相关配置。具体来说,代码实现了以下功能:

@Configuration(proxyBeanMethods = false)
public class SecuritySecureConfig {
    private final AdminServerProperties adminServer;
    private final SecurityProperties security;
    public SecuritySecureConfig(AdminServerProperties adminServer, SecurityProperties security) {
        this.adminServer = adminServer;
        this.security = security;
    }
    /**
     * 用于配置Spring Security的安全过滤器链,以及定义用户认证和授权的相关配置。
     * 通过这些配置,可以实现对不同URL路径的访问控制,以及用户的登录、注销和“记住我”等功能
     */
    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 配置安全过滤器链:定义了哪些URL路径需要进行认证,哪些路径可以匿名访问,以及如何处理登录、注销和CSRF防护
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
        http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests //
                        .requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/assets/**")))
                        .permitAll()
                        .requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/actuator/info")))
                        .permitAll()
                        .requestMatchers(new AntPathRequestMatcher(adminServer.path("/actuator/health")))
                        .permitAll()
                        .requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/login")))
                        .permitAll()
                        .dispatcherTypeMatchers(DispatcherType.ASYNC)
                        .permitAll()
                        .anyRequest()
                        .authenticated())
                /*
                formLogin:配置表单登录。
                loginPage:指定自定义的登录页面。
                successHandler:指定认证成功后的处理器。
                logout:配置注销功能。
                httpBasic:启用HTTP基本认证。
                 */
                .formLogin(
                        (formLogin) -> formLogin.loginPage(this.adminServer.path("/login")).successHandler(successHandler))
                .logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
                .httpBasic(Customizer.withDefaults());
        /*
         * addFilterAfter:在指定的过滤器之后添加自定义的CSRF过滤器。
         * csrf:配置CSRF防护。
         * csrfTokenRepository:设置CSRF令牌的存储方式。
         * csrfTokenRequestHandler:设置CSRF令牌的请求处理器。
         * ignoringRequestMatchers:忽略某些URL路径的CSRF防护。
         */
        http.addFilterAfter(new CustomCsrfFilter(), BasicAuthenticationFilter.class)
                .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                        .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
                        .ignoringRequestMatchers(
                                new AntPathRequestMatcher(this.adminServer.path("/instances"), "POST"),
                                new AntPathRequestMatcher(this.adminServer.path("/instances/*"), "DELETE"),
                                new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))
                        ));
        http.rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
        return http.build();
    }
    /*
    rememberMe:配置“记住我”功能。
    key:设置“记住我”功能的密钥。
    tokenValiditySeconds:设置“记住我”令牌的有效期。
     */
    @Bean
    public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = User.withUsername("macro")
                .password(passwordEncoder.encode("123456"))
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

自定义CSRF过滤器

public class CustomCsrfFilter extends OncePerRequestFilter {
    public static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";
    /**
     * 它是一个过滤器(Filter)的内部实现。
     * 该过滤器的主要功能是处理跨站请求伪造(CSRF)防护,确保每个请求都包含有效的CSRF令牌
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
        if (csrf != null) {
            Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME);
            String token = csrf.getToken();
            if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                cookie = new Cookie(CSRF_COOKIE_NAME, token);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        filterChain.doFilter(request, response);
    }
}

用于配置Spring Security的安全过滤器链,以及定义用户认证和授权的相关配置。通过这些配置,可以实现对不同URL路径的访问控制,以及用户的登录、注销和“记住我”等功能。

到此这篇关于SpringSecurity的安全过滤器链的文章就介绍到这了,更多相关SpringSecurity的安全过滤器链内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文