【问题标题】:Spring Security JWT validation without using UsernamePasswordAuthenticationToken不使用 UsernamePasswordAuthenticationToken 的 Spring Security JWT 验证
【发布时间】:2020-10-02 12:24:48
【问题描述】:

我需要编写我的自定义 Security Spring 过滤器来验证 JWT 令牌。

我有我的自定义 JWT 验证器。当令牌有效时,我必须授权用户。

我像其他在线展示的示例一样实现了这个:

UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user_id, null, null);

usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));  
                  SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

这很好,但我的问题是:是否有专门的 AuthenticationToken 用于 JWT 验证而不使用 UsernamePasswordAuthenticationToken?

我不喜欢使用 UsernamePasswordAuthenticationToken...这是个好习惯吗?

【问题讨论】:

    标签: java spring spring-security jwt


    【解决方案1】:

    当然,从干净代码的角度来看,它看起来并不好,因为它的名称 UsernamePasswordAuthenticationToken 与对象所做的事情不匹配。 JWT 与密码无关。就像你用橙色这个名字来指代苹果一样,也会让人困惑。

    JWT 通常用作 Bearer 令牌,spring-security-oauth2-resource-server 提供了一个 BearerTokenAuthenticationToken。但它会将所有其他 OAuth2 依赖项提取到您的项目中。所以如果你不需要 OAuth2 而只需要这个令牌类,只需自己创建一个。

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2020-01-04
      • 2022-08-16
      • 2016-11-15
      • 2021-01-20
      • 2011-11-14
      • 2018-05-30
      • 2019-02-07
      • 2021-01-27
      相关资源
      最近更新 更多