2

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)

Yuki Yoshida
  • 1,233
  • 1
  • 15
  • 28

1 Answers1

4

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();
} 
Yuki Yoshida
  • 1,233
  • 1
  • 15
  • 28
  • 1
    If your method is a @RequestMapping method, you can shove OAuth2Authentication in as an argument instead of trying to grab it from the SecurityContextHolder. – Phil Aug 11 '16 at 01:22