Spring MVC - 获取访问令牌

Spring MVC - Get access token

我正在添加 OAuth2.0 来保护我的 WebAPI。我正在尝试在用户登录时获取访问令牌。这就是我在登录后尝试获取用户信息的方式

@RequestMapping(value = "/login/{username}/{password}", method = RequestMethod.GET)
    public ResponseEntity<User> login(@PathVariable String username, @PathVariable String password) {
        if (!username.isEmpty() && !password.isEmpty()) {
            User user = userService.login(username, password);
            return new ResponseEntity<>(user, HttpStatus.OK);
        }

        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } 

这就是我实现获取访问令牌的代码的方式

<http pattern="/oauth/token" create-session="stateless"
          authentication-manager-ref="clientAuthenticationManager"
          xmlns="http://www.springframework.org/schema/security">
        <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
        <anonymous enabled="false" />
        <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
        <!-- include this only if you need to authenticate clients via request 
        parameters -->
        <custom-filter ref="clientCredentialsTokenEndpointFilter"
                       after="BASIC_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

当用户输入正确的用户名和密码时,我可以手动获取访问令牌。 现在我需要使用访问令牌显示用户详细信息,如下所示

{ "userId":14, "fullName":"Nishan Dhungana",
"email":"justin@live.com", "address":"Hokse", "contact":null,
"dob":null, "active":false, "createdAt":1519196604347,
"username":"nishanjjj41", "password":"nishan123" , 

"value":"7f228939-5f8e-4c29-b2d9-9ac78d0c16d8",
"expiration":1519542443387, "tokenType":"bearer" }

是否可以使用访问令牌获取用户详细信息

首先,将用户名和密码放在 url 中或将它们发回 JSON 是一个非常糟糕的主意。您无需再次发送。

要发送附加信息,您需要实施自定义令牌增强器:

public class CustomTokenEnhancer implements TokenEnhancer {

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    User principal = (User)authentication.getPrincipal();
    Map<String, Object> additionalInfo = new HashMap<>();

    // add more additional info
    additionalInfo.put("user_name", principal.getUsername());

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

    return accessToken;
}
}

然后将其连接到您的配置中:

<bean id="tokenEnhancer" class="com.security.CustomTokenEnhancer" />

<bean id="tokenServices" 
 class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
    <property name="tokenEnhancer" ref="tokenEnhancer" />
    // more properties
</bean>