SpringSecurityOAuth2(3) custom token information

GitHub address

Code cloud address

The default token return of OAuth2 only carries a maximum of 5 parameters (the client_credentials mode only has 4 parameters without refresh_token). The following is a return example:

{
    "access_token": "1e93bc23-32c8-428f-a126-8206265e17b2",
    "token_type": "bearer",
    "refresh_token": "0f083e06-be1b-411f-98b0-72be8f1da8af",
    "expires_in": 3599,
    "scope": "auth api"
}

Then the token we need may need to add custom parameters such as username:

{
    "access_token": "1e93bc23-32c8-428f-a126-8206265e17b2",
    "token_type": "bearer",
    "refresh_token": "0f083e06-be1b-411f-98b0-72be8f1da8af",
    "expires_in": 3599,
    "scope": "auth api",
    "username":"username"
}

The specific steps to implement a custom token are as follows: Create a new custom token with custom token information and return MyTokenEnhancer to implement the TokenEnhancer interface and rewrite the enhance method:

/**
 * @Description 自定义token返回值
 * @Author wwz
 * @Date 2019/07/31
 * @Param
 * @Return
 */
public class MyTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        final Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put("username", user.getUsername());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}

Then add MyTokenEnhancer to the authentication service configuration AuthorizationServerEndpointsConfigurer. The key point here is because I have specified defaultTokenServices() here, so I have to add configuration to this method

Also, if you have already generated a token without custom information, you need to delete the token in redis to test the result again, otherwise your result will always be wrong, because if the token has not expired, it will not be regenerated .

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324212715&siteId=291194637