【问题标题】:How to extract authentication token in @Controller如何在@Controller 中提取身份验证令牌
【发布时间】:2018-04-12 19:06:28
【问题描述】:

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

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

这里有 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";
    } 
}

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

【问题讨论】:

    标签: spring rest spring-security oauth single-sign-on


    【解决方案1】:

    如果你已经配置了 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();
    }
    

    希望对你有帮助!

    【讨论】:

    • 是的!这正是我所需要的!我通过实现此代码获得了我的令牌: OAuth2AuthenticationDetails = auth = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails(); accessToken = auth.getTokenValue();
    猜你喜欢
    • 2019-01-22
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多