spring-security:如何在 sso 登录期间获取 OAuth2 userInfo? [英] spring-security : How to get OAuth2 userInfo during sso logged in?

查看:34
本文介绍了spring-security:如何在 sso 登录期间获取 OAuth2 userInfo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过在 spring-boot:1.3.0.M1 上使用 @EnableOAuth2Sso 实现 oauth2 sso

I implement oauth2 sso by using @EnableOAuth2Sso on spring-boot:1.3.0.M1

我想使用我的资源服务器 (http://oauth2_resource_server/me) 中的 userInfo.

I want to use my userInfo from my resource server (http://oauth2_resource_server/me).

所以我尝试实现我自己的 ResourceServerTokenServices 参考UserInfoTokenServices

So I try to implement my own ResourceServerTokenServices refering to UserInfoTokenServices

@Configuration @EnableWebSecurity @EnableOAuth2Sso public class OAuth2Config {

  @Autowired ResourceServerProperties sso;

  @Bean public ResourceServerTokenServices userInfoTokenServices() {
    return new MyTokenService(sso.getUserInfoUri(), sso.getClientId());
  }
}

public class MyTokenService implements ResourceServerTokenServices {

  @Override public OAuth2Authentication loadAuthentication(String accessToken)
  throws AuthenticationException, InvalidTokenException {

    try {
      MyUser user = getFromNetworkAndSaveDB(accessToken);
      return extractAuthentication(user);
    } catch (Exception e) {
      throw new InvalidTokenException(e.getMessage(), e);
    }
  }

  /**
   * @param user retrieved and serialize from http://oauth2_resource_server/me
   */
  private OAuth2Authentication extractAuthentication(MyUser user) {

    List<GrantedAuthority> authorities =
      AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");

    OAuth2Request request =
      new OAuth2Request(null, this.clientId, null, true, null, null, null, null, null);

    UsernamePasswordAuthenticationToken token =
      new UsernamePasswordAuthenticationToken(user.getId(), "N/A", authorities);
    token.setDetails(user);

    return new OAuth2Authentication(request, token);
  }
}

上面的代码正在创建 OAuth2Authentication 对象并且它可以工作.

above code is creating OAuth2Authentication object and it works.

我想在登录时使用 MyUser 对象,但我该怎么做?(我不知道什么是通用方式)

I want to use MyUser object while logged in, but How can I do this ? (I don't know what is generic way)

推荐答案

OAuth2 SSO 登录后,我终于可以在下面获得我的用户信息了.

Finally I can get my user info below, after OAuth2 SSO Logged in.

MyUser findFromContext() {

  OAuth2Authentication oAuth2Authentication =
    (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();

  Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();

  return (MyUser) userAuthentication.getDetails();
} 

这篇关于spring-security:如何在 sso 登录期间获取 OAuth2 userInfo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆