在请求之前验证JWT令牌

时间:2020-07-20 15:53:27

标签: spring-boot jwt

我正在编写一个API,该API必须验证JWS是否具有有效的签名并且它没有过期-我的项目有几条路由,并且只有一条路由受保护。

我已经创建了一个过滤器:


@Component
class JWTFilter : OncePerRequestFilter() {

    override fun doFilterInternal(req: HttpServletRequest, resp: HttpServletResponse, chain: FilterChain) {
        // code to validate JWT
        chain.doFilter(req, resp)
    }

}

还有SecConfig:

@Configuration
@EnableWebSecurity
class SecConfig(val authRequestFilter: AuthRequestFilter) : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http
            .authorizeRequests()
            .antMatchers("/cash")
            .authenticated()
            .anyRequest()
            .permitAll()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

        http.addFilterBefore(authRequestFilter, <WhatShouldIPutHere.class>)
    }
}

我已经创建了SecConfig类来集中所有配置,并且我的API没有任何类型的登录,我只收到JWS令牌,并且需要确保其有效。

<WhatShouldIPutHere.class>中使用的正确实现是什么?

编辑:

它可以工作,但是如果我的应用程序中没有用户名/密码验证,那么UsernamePasswordAuthenticationFilter的用途是什么?

http.addFilterBefore(authRequestFilter, UsernamePasswordAuthenticationFilter::class.java)

编辑2:

为什么要验证每个请求?我只想验证/cash

2 个答案:

答案 0 :(得分:0)

它可以工作,但是如果我的应用程序中没有Username / Pw身份验证,使用UsernamePasswordAuthenticationFilter有什么用呢?

它告诉spring您要将JWT过滤器放置在过滤器链中的哪个位置。参见filter ordering。更具体地说,使用addFilterBefore这样会将您的过滤器放在UsernamePasswordAuthenticationFilter之前。

为什么要验证每个请求?我只想验证/ cash

因为您尚未在此行中配置任何特定路径:

http.addFilterBefore(authRequestFilter, UsernamePasswordAuthenticationFilter::class.java)

使用http.antMatchers("/cash").addFilterBefore...

答案 1 :(得分:-1)

您必须使用:

org.springframework.web.filter.OncePerRequestFilter