【问题标题】:Validate JWT token before request在请求之前验证 JWT 令牌
【发布时间】:2020-11-09 22:23:49
【问题描述】:

我正在编写一个 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 令牌,我需要确保它是有效的。

&lt;WhatShouldIPutHere.class&gt; 中使用的正确实现是什么?

编辑:

它有效,但如果我的应用程序中没有用户名/密码验证,那么使用 UsernamePasswordAuthenticationFilter 有什么意义?

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

编辑 2:

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

【问题讨论】:

    标签: spring-boot jwt


    【解决方案1】:

    它有效,但如果我的应用程序中没有用户名/密码验证,那么使用 UsernamePasswordAuthenticationFilter 有什么意义?

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

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

    因为你没有在这一行配置任何具体的路径:

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

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

    【讨论】:

      【解决方案2】:

      你必须使用:

      org.springframework.web.filter.OncePerRequestFilter
      

      【讨论】:

      • 它使应用程序崩溃:Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class org.springframework.web.filter.OncePerRequestFilter
      • 另外,我的过滤器已经扩展 OncePerRequestFilter
      • 尝试一下:OncePerRequestFilter::class.java
      • 抛出异常Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class org.springframework.web.filter.OncePerRequestFilter
      猜你喜欢
      • 2021-09-17
      • 2019-09-16
      • 2019-04-02
      • 2016-03-29
      • 2021-11-02
      • 2020-09-20
      • 2020-09-12
      • 2019-06-23
      • 2019-10-06
      相关资源
      最近更新 更多