【问题标题】:My authenticationTokenFilterBean is getting called on non protected endpoints我的 authenticationTokenFilterBean 在非受保护的端点上被调用
【发布时间】:2019-04-17 10:55:16
【问题描述】:

上下文:我正在使用springspring security 构建一个API 来保护我的endpoints

我的尝试:我创建了一个WebSecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class WebSecurityConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    private lateinit var unauthorizedHandler: JwtAuthenticationEntryPoint

    @Qualifier("jwtUserDetailsServiceImpl")
    @Autowired
    private lateinit var userDetailsService: UserDetailsService

    @Autowired
    @Throws(Exception::class)
    fun configureAuthentication(authenticationManagerBuilder: AuthenticationManagerBuilder) {
        authenticationManagerBuilder.userDetailsService<UserDetailsService>(this.userDetailsService).passwordEncoder(passwordEncoder())
    }

    @Bean
    @Throws(Exception::class)
    fun customAuthenticationManager(): AuthenticationManager {
        return authenticationManager()
    }

    @Bean
    fun passwordEncoder(): PasswordEncoder {
        return BCryptPasswordEncoder()
    }

    @Bean
    @Throws(Exception::class)
    fun authenticationTokenFilterBean(): JwtAuthenticationTokenFilter {
        return JwtAuthenticationTokenFilter()
    }

    @Throws(Exception::class)
    override fun configure(httpSecurity: HttpSecurity) {
        httpSecurity.csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/api/user/**").permitAll()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .antMatchers("/api/auth/**").permitAll()
                .anyRequest().authenticated()
        httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter::class.java)
        httpSecurity.headers().cacheControl()
    }
}

我的问题:我的authenticationTokenFilterBean 正在由 api/user 启动的端点被调用,因为我正在做("/api/user/**").permitAll() 这应该发生吗?因为这是在调用我的JwtAuthenticationTokenFilter(上图),而我的 authToken 始终是 null,因为我没有在 Authorization 标头中传递任何内容(因为这是一个帐户创建,这就是为什么我将 permitAll 放在此端点 @ 987654332@

class JwtAuthenticationTokenFilter : OncePerRequestFilter() {

    @Qualifier("jwtUserDetailsServiceImpl")
    @Autowired
    private lateinit var userDetailsService: UserDetailsService

    @Autowired
    private lateinit var jwtTokenUtil: JwtTokenUtil

    @Throws(ServletException::class, IOException::class)
    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
        val authToken = request.getHeader("Authorization")
        val username = jwtTokenUtil.getUsernameFromToken(authToken)

        if (username != null && SecurityContextHolder.getContext().authentication == null) {
            val userDetails = this.userDetailsService.loadUserByUsername(username)
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                val authentication = UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.authorities)
                authentication.details = WebAuthenticationDetailsSource().buildDetails(request)
                logger.info("authenticated user $username, setting security context")
                SecurityContextHolder.getContext().authentication = authentication
            }
        }
        chain.doFilter(request, response)
    }
}

目标: 谁能帮我发现我的 authenticationTokenFilterBean 在非受保护的 API 上被调用是否正常。如果是解释我该怎么做。谢谢

【问题讨论】:

标签: spring spring-security jwt


【解决方案1】:

对未受保护的端点的请求仍将通过整个过滤器链,其中包括您的过滤器。 permitAll() 表示FilterSecurityInterceptor 将允许未经身份验证的用户访问端点,但不影响请求通过哪些过滤器。

.antMatchers("/api/auth/**").permitAll() //allow unauthenticated users

如果您希望您的过滤器仅适用于某些请求,您可以添加一个RequestMatcher,该RequestMatcher 在您的过滤器的构造函数中初始化,并具有要匹配的特定路径。例如,new NegatedRequestMatcher(new AntPathRequestMatcher("/api/user/**")) 将匹配除未受保护的端点之外的任何路径。然后在doFilterInternal() 你可以这样做:

if(!requestMatcher.matches(request)) {
    chain.doFilter(request, response);
    return;
}
// ... the rest of your logic

现在您的过滤器将仅在请求不是所需的"/api/user/**" 时触发。

【讨论】:

    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多