2017-02-17 34 views
2

我正在使用彈簧安全性OAuth2使用JWT令牌一段時間,但現在需要將2個用戶定義的值添加到JWT令牌。將用戶數據添加到JWT負載以實現彈性安全OAUth2

所以當我向request/oauth/token增加了一組參數時?grant_type = client_credentials & user_value = 1234567890。

上面的user_value是爲了說明的目的。我可以將它追蹤到我的CustomTokenEnhancer中(我將它作爲一種傳遞此信息的途徑)。通過傳遞給我的CustomTokenEnhancer的OAuth2Authentication身份驗證,可以看到所有請求參數。

現在我可以將這些信息添加到我看到的作爲令牌請求一部分返回給我的附加信息中。見下文。

{ 
    "access_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicGhpLWFwaSJdLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwib3JnYW5pemF0aW9uIjoicGhpLXVzZXJtZ3RuIiwidXNlcl90b2tlbiI6IjEyMzQ1Njc4OTAiLCJleHAiOjE0ODczNjc2NzEsImF1dGhvcml0aWVzIjpbIlJPTEVfQ0xJRU5UIl0sImp0aSI6IjFlZDMzZTAxLTc1ZGUtNDNjZC1hMzk2LTFkMzk2N2Y1NDQ5OCIsImNsaWVudF9pZCI6InBoaS11c2VyIn0.p628BNaaGljypEcGXZMkstNeTN-221qzzNQQ0npxDLTszWaXkgXqsBnBbKf9XMEtWTeCQkIszC9ne1Ei2X5IWTskhLT9Rko-8K7Jq-mXUc6HJZW-3tGV5rRer8Eyyw1wysW9Jiyp7sPkN-TIx12A70f_LHm6PrRR4ECppHWADs-2DvYA30p8omT1_RTt2WlqC40mopUN2TBPkb1WulVpOUEpcP358Ox8oVP8VQRSkLGZKB_b0KZAK9KGjLg6WNh8RghZaBuYuJQpITe_0XEBs_JfwrHhcK1IGaoYwSS7IGp3Cima9OMljdzayDKRqlfSl3WhaBuFmD1S37p-OVQL0A", 
    "token_type":"bearer", 
    "expires_in":8967, 
    "scope":"read write", 
    "user_value":"1234567890", 
    "jti":"1ed33e01-75de-43cd-a396-1d3967f54498" 
} 

但我不希望這些值以這種方式可見。我希望它們被添加到加密的令牌中。

我花了一些時間看,它不清楚我實際上如何添加。這應該是可能的,不是嗎?

回答

3

裏面自己TokenEnhancer則必須再次對其進行編碼:

@Override 
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 
    // Generate additional Information [...] 


    // Write it to the token 
    ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(addInfo); 

    // Encode Token to JWT 
    String encoded = super.encode(accessToken, authentication); 

    // Set JWT as value of the token 
    ((DefaultOAuth2AccessToken) accessToken).setValue(encoded); 

    return accessToken; 
} 

你可以用JwtHelper方法解決這個問題,但我只是擴展了JwtAccessTokenConverter,所以我可以使用編碼和解碼。

當實例化你的令牌增強,你必須添加倉庫信息:

private CustomTokenEnhancer jwtCustomEnhancer() { 
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "***".toCharArray()); 
    CustomTokenEnhancer converter = new CustomTokenEnhancer(); 
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt")); 

    return converter; 
} 
1

我做了類似的事情,在用戶詳細信息服務(而不是令牌增強器)的幫助下將值作爲授予的權限傳遞。在客戶端,我編寫了一個提取器來檢索Spring注入的主體的值,類型爲OAuth2Authentication。下面的代碼是Scala,但你可以很容易適應的Java:

/** 
 
    * Mix-in to implicitly extract entity or identity from the principal. 
 
    */ 
 
trait AuthorityExtractor { 
 

 
    def _contextName(implicit principal: OAuth2Authentication) = id(principal, "CONTEXT_") 
 

 
    def _entityId(implicit principal: OAuth2Authentication) = id(principal, "ENTITY_ID_") 
 

 
    def _userId(implicit principal: OAuth2Authentication) = id(principal, "USER_ID_") 
 

 
    def _identityId(implicit principal: OAuth2Authentication) = id(principal, "SELF_ID_") 
 

 
    private def id(principal: OAuth2Authentication, prefix: String) = { 
 
    import collection.JavaConversions._ 
 
    principal 
 
     .getAuthorities 
 
     .filter(_.toString.startsWith(prefix)) 
 
     .map(_.toString.substring(prefix.length)) 
 
     .headOption.getOrElse("") 
 
    } 
 

 
}

-1

我延長JwtAccessTokenConverter類是這樣的:

public class FooJwtAccessTokenConverter extends JwtAccessTokenConverter { 
    @Override 
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 
    DefaultOAuth2AccessToken fooAccessToken = new DefaultOAuth2AccessToken(accessToken); 
    fooAccessToken.getAdditionalInformation().put("foo_property", "foo"); 
    return super.enhance(scaAccessToken, authentication); 
    } 

在我AuthotizationServerConfig我創建這個:

@Override 
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 
    endpoints 
      .tokenStore(tokenStore()) 
      .accessTokenConverter(accessTokenConverter()) 
      .authenticationManager(authenticationManager); 
} 

@Bean 
public TokenStore tokenStore() { 
    return new JwtTokenStore(accessTokenConverter()); 
} 

@Bean 
public JwtAccessTokenConverter accessTokenConverter() { 
    ScaJwtAccessTokenConverter accessTokenConverter = new ScaJwtAccessTokenConverter(); 
    accessTokenConverter.setSigningKey("familia-mgpe"); // Parte da string de validação do token JWT. 
    return accessTokenConverter; 
} 
相關問題