spring-security : How to get OAuth2 userInfo during sso logged in?

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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

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

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);   } } 

above code is creating OAuth2Authentication object and it works.

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

回答1:

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(); }  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!