如何在@Controller 中提取身份验证令牌

How to extract authentication token in @Controller

我有 Spring 使用 OAuth 2.0 和授权服务器的启动应用程序。当我尝试访问安全页面时,我在我的授权服务器(Blitz 身份提供者)的登录页面上得到了重定向,并且这里的一切都像它应该的那样运行良好。我的问题是我无法在@Controller(在安全页面上) 中提取授权令牌。我想稍后在第二个应用程序中使用该令牌进行授权。

这里有 2 个文件,可以帮助您理解我的部分上下文。

application.yml

server:
  port: 8080
  context-path: /
  session:
    cookie:
      name:FIRSTSESSION
security:
  basic:
    enabled: false
  oauth2:
    client:
      clientId: test_id
      clientSecret: f3M5m9a2Dn0v15l
      accessTokenUri: http://server:9000/blitz/oauth/te
      userAuthorizationUri: http://server:9000/blitz/oauth/ae?scope=test_scope
    resource:
      userInfoUri: http://server:9000/blitz/oauth/me
logging:
  level:
    org.springframework.security: DEBUG

SsoController.java

@EnableOAuth2Sso
@Controller
public class SsoController {

    @RequestMapping("/secondService")
    public String getContent(HttpServletRequest request, Model model) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        model.addAttribute("submittedValue", authentication.getDetails());
        return "secondService";
    } 
}

那么,您有什么建议吗?在这种情况下如何提取授权令牌?

如果您配置了 oauth2 authorization/resource 服务器,您可以尝试以下代码:

@Autowired
private TokenStore tokenStore;

@RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/oauth/me")
public Map<String, Object> userInfo(OAuth2Authentication auth){
    final OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
    //token
    String accessToken = details.getTokenValue();
    //reference
    final OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue());
   // clientid
    String clientId = auth.getOAuth2Request().getClientId();
}

希望对您有所帮助!