【问题标题】:Spring MVC - Get access tokenSpring MVC - 获取访问令牌
【发布时间】:2018-08-04 21:44:28
【问题描述】:

我正在添加 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" }

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

【问题讨论】:

    标签: rest spring-mvc spring-security-oauth2


    【解决方案1】:

    首先,将用户名和密码放在 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>
    

    【讨论】:

    • CustomTokenEnhancer 类的目的是什么。
    • 与令牌一起发送有关用户的其他信息。
    • 我还有一个问题如何访问我的控制器内的令牌值
    猜你喜欢
    • 2020-04-09
    • 2014-07-09
    • 2018-02-17
    • 1970-01-01
    • 2016-10-22
    • 2018-06-18
    相关资源
    最近更新 更多