(五)SpringCloud+Security+Oauth2--自定义ResourceServerTokenServices优化oauth2性能

一 性能瓶颈

通过前面的分析我们知道了oath2在对token进行校验的时候会向客户端端发送一次token校验的请求,这样一来会造成认证中心的负载压力过大,成为造成整个系统瓶颈的关键点
在这里插入图片描述
在这里插入图片描述
我们可以自定义一个ResourceServerTokenServices直接从tokenstore中去获得Authcation
加载到安全上下文即可

二 自定义ResourceServerTokenServices

@RequiredArgsConstructor
@Component
@Primary
public class LocalResourceTokenServices implements ResourceServerTokenServices {
    
    
    private final TokenStore tokenStore;

    @Override
    public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
    
    
        OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(accessToken);
        if (Objects.isNull(oAuth2Authentication)){
    
    
            return null;
        }
        oAuth2Authentication.setAuthenticated(true);
        return oAuth2Authentication;
    }

    @Override
    public OAuth2AccessToken readAccessToken(String accessToken) {
    
    
        throw new UnsupportedOperationException("Not supported: read access token");
    }
}

注意要加上@Primary保证在token校验时强制使用该实现

猜你喜欢

转载自blog.csdn.net/Instanceztt/article/details/128202066