spring-security 在OncePerRequestFilter中排除某些API路由- Spring安全性

s71maibg  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(381)

WebSecurityConfigurer '方法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
        .exceptionHandling().authenticationEntryPoint(this.authEntryPoint).and()
        .formLogin().disable()
        .logout().permitAll()
        .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests().antMatchers("/user/create", "/login", "/logout", "/user/token/refresh").permitAll().and()
        .authorizeRequests().antMatchers("/tag/**").permitAll().and()
        .authorizeRequests().antMatchers("/post/**").permitAll().and()
        .authorizeRequests().antMatchers("/post/file/create", "/post/file/create").hasAnyRole("ROLE_USER", "ROLE_ADMIN")
        .anyRequest().authenticated();
    http.addFilter(new AuthenticationTokenFilter(
        authenticationManagerBean(),
        this.userService,
        this.userMapper,
        this.accessor,
        this.secret, 
        this.claim, 
        this.accessTokenExpirationTimeMillis, 
        this.refreshTokenExpirationTimeMillis));
    http.addFilterBefore(this.authorizationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}

正如您所看到的,我配置了某些路由以排除身份验证(例如“/tag/**”)。

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    if (request.getServletPath().equals("/login") 
        || request.getServletPath().equals("/logout") 
        || request.getServletPath().equals("/user/token/refresh")
        || request.getServletPath().equals("/user/create")
        || request.getServletPath().equals("/tag/")
        || request.getServletPath().matches("/post/[a-zA-Z0-9]{12}")
        || request.getServletPath().matches("/post/[a-zA-Z0-9]{12}/comments")) {
        filterChain.doFilter(request, response);
    } else {
        // do authorization process
    }
}

当前的实现是通过检查servletPath来忽略给定OncePerRequestFilter中的某些路由。有没有其他方法可以从OncePerRequestFilter中排除某些API路由?因为每次添加新的自由身份验证路由时,我都必须在if语句中添加它们,这感觉不像是正确的做法。

qgzx9mmu

qgzx9mmu1#

使用不像这样的安全保护URI

if(appSecuredUriList.stream().anyMatch(uri -> !uri.equals(request.getServletPath())))
    filterChain.doFilter(request, response);
else {
    // do authorization process
}

或者将它们添加到数据库或其他存储库中并进行缓存

if(cachedIgnoreList.stream().anyMatch(uri -> uri.equals(request.getServletPath())))
        filterChain.doFilter(request, response);
else {
                // do authorization process
}

相关问题