我现在部署了两个Spring Boot微服务:
Auth Gateway在成功登录后发出jwt令牌。对于下一个请求,它会在将请求重定向到业务逻辑之前验证/授权jwt令牌。
从Auth Gateway到其他服务共享用户相关信息的最佳方式是什么?
使用SpringSecurity和Spring Boot编写Auth Gateway
之间。
答案 0 :(得分:2)
在JWT令牌中编码所有必要的详细信息(用户ID等)。
您在Auth网关中发出令牌,JWT Access令牌包含三个部分:标题,声明和签名
将所有必要的信息放入声明部分。见the example
@Component
public class JwtTokenFactory {
private final JwtSettings settings;
@Autowired
public JwtTokenFactory(JwtSettings settings) {
this.settings = settings;
}
/**
* Factory method for issuing new JWT Tokens.
*
* @param username
* @param roles
* @return
*/
public AccessJwtToken createAccessJwtToken(UserContext userContext) {
if (StringUtils.isBlank(userContext.getUsername()))
throw new IllegalArgumentException("Cannot create JWT Token without username");
if (userContext.getAuthorities() == null || userContext.getAuthorities().isEmpty())
throw new IllegalArgumentException("User doesn't have any privileges");
Claims claims = Jwts.claims().setSubject(userContext.getUsername());
claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));
DateTime currentTime = new DateTime();
String token = Jwts.builder()
.setClaims(claims)
.setIssuer(settings.getTokenIssuer())
.setIssuedAt(currentTime.toDate())
.setExpiration(currentTime.plusMinutes(settings.getTokenExpirationTime()).toDate())
.signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
.compact();
return new AccessJwtToken(token, claims);
}