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

Art*_*oon 5 rest spring oauth spring-security single-sign-on

我有使用OAuth 2.0和授权服务器的Spring Boot应用程序。当我尝试访问安全页面时,我在我的授权服务器(Blitz Identity Provider)的登录页面上获得了重定向,并且一切在这里都能正常运行。我的问题是我无法在@Controller(在安全页面上)中提取授权令牌。我想稍后在第二个应用程序中使用该令牌进行授权。

  • 尝试了一下(在回答中),它起作用了,我取回了我的令牌,但是如您所见,它是用户名和密码参数的硬编码,就像通过登录登录-我不需要第二次登录(在经过身份验证的页面上)。
  • 试图输出authentication.getDetails(),它显示令牌类型和令牌,如<TOKEN>,但这还不够。
  • 尝试在请求响应标头中查找令牌,但没有找到它,因此授权服务器不会在标头中发送令牌。

这里有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
Run Code Online (Sandbox Code Playgroud)

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";
    } 
}
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*mir 7

如果您已配置 oauth2 授权/资源服务器,您可以尝试以下代码:

@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();
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!