我将这项任务作为公司的实习生在他们的系统上实施刷新令牌。我可以看到已经为它制作了一些代码(有人已经尝试过实现它),但是它没有用。
我跟踪代码,发现它在控制台上创建并打印刷新令牌,但不在ResponseEntity上打印(返回null)。我不习惯在Java EE,Spring Framework,JWT Tokens或OAuth中编码。我还有很多东西需要学习。我看到了一些答案,它需要一个脱机的访问类型,但代码都是PHP。我不知道如何使用Spring Framework在Java上实现它。所以这里有一些代码......
对于登录控制器:
public ResponseEntity<String> auth(@RequestBody AuthModel auth) {
String username = auth.getUsername();
String password = auth.getPassword();
UserModel user = authService.authenticate(username, password);
if (user != null) {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
auth.getUsername(),
auth.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication); //set current user
final UserDetails userDetails = authService.loadUserByUsername(auth.getUsername());
user.setOrg_id(usrService.setOrgId(user.getCompany_id()));
return new ResponseEntity(new ResponseModel(HttpStatus.OK.value(),jwtService.getToken(userDetails),jwtService.getRefreshToken(userDetails), "Success"), HttpStatus.OK);
}
对于服务:
@SuppressWarnings("static-access")
public String getRefreshToken(UserDetails user)
{
System.out.println("Get Refresh Token: " + createRefreshToken(user));
return createRefreshToken(user);
}
public String createRefreshToken(UserDetails userDetails) {
if (userDetails.getUsername() == null) {
throw new IllegalArgumentException("Cannot create JWT Token without username");
}
Claims claims = Jwts.claims().setSubject(userDetails.getUsername());
claims.put("roles", Arrays.asList(userDetails.getAuthorities()));
Date now = new Date();
String token = Jwts.builder()
.setClaims(claims)
.setSubject(userDetails.getUsername())
.setId(UUID.randomUUID().toString())
.setIssuedAt(now)
.setExpiration(getRefreshExpirationTime())
.signWith(SignatureAlgorithm.HS512, refreshEncodedSecret)
.compact();
//System.out.println("Refresh Token: " + token);
return token;
}
成功登录后,会返回此响应。
对于控制台......
我希望你能详细回答我。提前谢谢!