在 Oauth2 中使用用户名验证访问令牌

validate access token with user name in Oauth2

我正在尝试为我的 SPA 应用程序实施 OAuth2 身份验证。我面临一个问题,例如有两个用户,user1 和 user2 都已登录。当 user1 尝试使用 user2 access token 时,user1 可以访问 .我不知道如何保护访问令牌。

用户每次使用oauth2认证登录时,都会将新登录用户的user-id关联到一个唯一的access_token,可以得到那个user_id,并且依次将其与当前登录用户的 user_id 映射,以查明该用户是否正在使用他自己的 access_token.

我找到解决办法了。 要自定义访问令牌,我们可以保护用户访问令牌。 我已经使用 Token enhancer 自定义了访问令牌。 代码如下

@Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setTokenEnhancer(tokenEnhancer());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

自定义增强器会像

 public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    AppUserDetails appUserDetails = (AppUserDetails) authentication.getPrincipal();
    final Map<String, Object> additionalInfo = new HashMap<>();
    String encodedBytes = Base64.getEncoder().encodeToString(appUserDetails.getIdUser().toString().getBytes());
    additionalInfo.put("authorities", appUserDetails.getAuthorities());
    additionalInfo.put("username", appUserDetails.getUsername());
    additionalInfo.put("idUser", encodedBytes);
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}

在其他方法中,我已经解码了自定义访问令牌。 我还使用了 AuthorizationServerEndpointsConfigurer

@Override
    //Configure the properties and enhanced functionality of the Authorization Server endpoints.
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore()).tokenEnhancer(tokenEnhancer()).authenticationManager(authenticationManager);
    }