问题描述
我有一个 JHipster 微服务,它具有基于 UAA 的身份验证 (OAuth 2.0)。我已通过 IatTokenEnhancer
在令牌中设置了某些声明。我想在每个请求中使用这些声明的值。 How can I fetch the access token from current request?
解决方法
令牌可通过 SecurityContext
访问。代码如下:
public static Optional<String> getCurrentUserToken() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.filter(authentication -> authentication.getDetails() instanceof OAuth2AuthenticationDetails)
.map(authentication -> ((OAuth2AuthenticationDetails) authentication.getDetails()).getTokenValue());
}