我最近在我的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中添加角色?
我从代码中了解到,当登录请求到来时,它包含userName
和password
,ObjectMapper
将其Map到指定的类之一。那么,我如何从数据库中提取该用户的角色呢?
2条答案
按热度按时间mrwjdhj31#
从身份验证获取角色
那么您可以创建一个Helper类来保存用户和角色的数据,并将该类用作JwtsBuilder的主题。
7cwmlq892#
使用claim(“key”,“Value”)。这将为您的JWT的声明添加角色。
例如:JWT声明如下所示
//索赔{“子”:“test@example.com“,“名称”:“测试示例”,“角色”:“用户”}
请尝试以下代码片段。
让我们知道是否可行。