2015-07-10 387 views
2

我實現的oauth2通過對彈簧引導使用@EnableOAuth2Sso SSO:1.3.0.M1spring-security:如何在sso登錄時獲取OAuth2 userInfo?

我想用我的用戶信息從我的資源服務器(http://oauth2_resource_server/me)。

所以我嘗試實現自己ResourceServerTokenServices指的 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對象和它的作品。

我想在登錄時使用MyUser對象,但我該怎麼做? (我不知道什麼是通用的方式)

回答

4

最後,我可以讓我的用戶信息下方,之後的OAuth2 SSO登錄。

MyUser findFromContext() { 

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

    Authentication userAuthentication = oAuth2Authentication.getUserAuthentication(); 

    return (MyUser) userAuthentication.getDetails(); 
} 
+1

如果你的方法是一個@RequestMapping方法,可以作爲一個參數,而不是試圖從抓住它推OAuth2Authentication SecurityContextHolder中。 – Phil