spring-security JWT中基于角色的授权

xtupzzrd  于 2022-11-11  发布在  Spring
关注(0)|答案(2)|浏览(242)

我最近在我的Sping Boot 应用程序中实现了带有Spring Security的JWT身份验证。

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

  private AuthenticationManager authenticationManager;

  public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
  }

  @Override
  public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
      throws AuthenticationException {
    try {
      UserModel creds = new ObjectMapper().readValue(req.getInputStream(), UserModel.class);

      return authenticationManager.authenticate(
          new UsernamePasswordAuthenticationToken(creds.getMobileNumber(),
              creds.getPassword(), new ArrayList<>()));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res,
      FilterChain chain,
      Authentication auth) throws IOException, ServletException {

    String token = Jwts.builder().setSubject(((User) auth.getPrincipal()).getUsername())
        .setExpiration(new Date(System.currentTimeMillis() + 360000000))
        .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET).compact();
    res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
    res.setStatus(HttpServletResponse.SC_OK);
    String tokenJsonResponse = new ObjectMapper().writeValueAsString("Ok");
    res.addHeader("Content-Type", "application/json");
    res.getWriter().print(tokenJsonResponse);
  }
}

我想在发送JWT之前向其添加角色。如何在JWT中添加角色?
我从代码中了解到,当登录请求到来时,它包含userNamepasswordObjectMapper将其Map到指定的类之一。那么,我如何从数据库中提取该用户的角色呢?

mrwjdhj3

mrwjdhj31#

从身份验证获取角色

Set<String> roles = authentication.getAuthorities().stream()
     .map(r -> r.getAuthority()).collect(Collectors.toSet());

那么您可以创建一个Helper类来保存用户和角色的数据,并将该类用作JwtsBuilder的主题。

7cwmlq89

7cwmlq892#

使用claim(“key”,“Value”)。这将为您的JWT的声明添加角色。
例如:JWT声明如下所示
//索赔{“子”:“test@example.com“,“名称”:“测试示例”,“角色”:“用户”}
请尝试以下代码片段。

String token = Jwts.builder().setSubject(((User) auth.getPrincipal()).getUsername())
                 .claim("role", "user")
                .setExpiration(new Date(System.currentTimeMillis() + 360000000))
                .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET).compact();

让我们知道是否可行。

相关问题