我正在尝试在我的 JWT 中分配一个角色,但没有这样做。 我的用户实体中有一个如下所示的角色:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role;
getters and setters...
}
我在数据库中的用户是这样的:
INSERT INTO user(id, username, password, role, active) VALUES(1,'test1','securePassword','ADMIN', true);
这是我生成令牌的类。
@Service
public class JwtUtil {
private String SECRET_KEY = "secureKey";
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
*我知道密钥应该在属性文件中,但这只是一个临时解决方案。
在方法中
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
有人声称,此时是一个空的 HashMap。
我如何将我的角色分配给他们?
这是我的身份验证端点,返回一个 JWT 作为响应
@RequestMapping(value = "/auth", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody UsernameAndPasswordAuthenticationRequest authenticationRequest) throws Exception {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())
);
}
catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password", e);
}
final UserDetails userDetails = myUserDetailsService
.loadUserByUsername(authenticationRequest.getUsername());
System.out.println(userDetails);
final String jwt = jwtUtil.generateToken(userDetails);
return ResponseEntity.ok(new UsernameAndPasswordAuthenticationResponse(jwt));
}
我是 JWT 的新手,很难理解它的结构。
如有任何提示或其他阅读材料,我们将不胜感激。