PAYATHON 2026

Spring Security OAuth2 失败处理器如何获取失败请求所用 Token

数据小陈

结论:在 Spring Security 7.1.1 中,失败回调的第一个参数 OAuth2AuthorizationFailure 已经包含本次请求实际使用的 OAuth2AuthorizedClient。不要在 OAuth2AuthorizationFailureHandler 里重新从 service 读取当前缓存。用 failure.getAuthorizedClient() 拿到 T1,再对 store 做“token 相等才删除”的原子条件删除。这样,失败属于 T1 而缓存已是 T2 时不会删掉 T2;缓存仍是 T1 时则正常失效。

原因

OAuth2ClientHttpRequestInterceptor 在发请求前通过 OAuth2AuthorizedClientManager 解析出 authorized client,用它设置 Authorization: Bearer T1,然后把同一个 authorized client 放进 OAuth2AuthorizationFailure 交给 handler。service 里的缓存可能已经被并发调用方改成 T2,所以 loadAuthorizedClient(...) 读到的是当前缓存,不是失败请求发出时的 token。非 Servlet 场景下 attributes 为空很正常,不必通过它传 token。

处理步骤

  1. 在 handler 中取 failure.getAuthorizedClient(),拿到失败请求使用的 token。
  2. 用 registrationId、principalName 和 token 值调用自定义 service 的原子条件删除方法。
  3. 只有当前缓存 token 与失败 token 完全相等时才删除;否则不做任何操作,保留 T2。
  4. 不要在 handler 里先 load 再 remove。两步之间可能有并发 save 插进来,导致误删替代 token。

代码示例

失败 handler:

interceptor.setAuthorizationFailureHandler((failure, authentication, attributes) -> {
    OAuth2AuthorizedClient failedClient = failure.getAuthorizedClient();
    String failedToken = failedClient.getAccessToken().getTokenValue();

    String registrationId = failedClient.getClientRegistration().getRegistrationId();
    String principalName = failedClient.getPrincipalName(); // 通常等同于 authentication.getName()

    boolean removed = service.removeAuthorizedClientIfTokenMatches(
            registrationId, principalName, failedToken);

    System.out.println("failed=" + failedToken);
    System.out.println("removed=" + removed);
});

如果使用自己的 service,可以用 ConcurrentHashMap.computeIfPresent 做原子比较删除:

public final class TokenAwareAuthorizedClientService implements OAuth2AuthorizedClientService {
    private final ConcurrentMap<String, OAuth2AuthorizedClient> clients = new ConcurrentHashMap<>();

    private static String key(String registrationId, String principalName) {
        return registrationId + "::" + principalName;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String registrationId,
                                                                     String principalName) {
        return (T) clients.get(key(registrationId, principalName));
    }

    @Override
    public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient,
                                     Authentication principal) {
        clients.put(key(authorizedClient.getClientRegistration().getRegistrationId(),
                principal.getName()), authorizedClient);
    }

    @Override
    public void removeAuthorizedClient(String registrationId, String principalName) {
        clients.remove(key(registrationId, principalName));
    }

    public boolean removeAuthorizedClientIfTokenMatches(String registrationId,
                                                        String principalName,
                                                        String expectedToken) {
        AtomicBoolean removed = new AtomicBoolean(false);
        clients.computeIfPresent(key(registrationId, principalName), (k, current) -> {
            String currentToken = current.getAccessToken().getTokenValue();
            if (expectedToken.equals(currentToken)) {
                removed.set(true);
                return null;
            }
            return current;
        });
        return removed.get();
    }
}

如果还得继续用 InMemoryOAuth2AuthorizedClientService,包装层就要对同一个 registrationId/principalName 的 save、remove 和条件删除使用同一把按 key 的锁。只给 remove 加锁而 save 不加锁仍会出问题:可能先读到 T1,随后被写入 T2,最后误删 T2。

验证结果

按上面的顺序处理时:

  • 失败请求使用 T1。
  • handler 从 failure.getAuthorizedClient() 取得 T1。
  • 当前缓存是 T2。
  • removeAuthorizedClientIfTokenMatches(..., T1) 返回 false,T2 保留。
  • 如果当前缓存仍是 T1,则返回 true 并删除 T1。

注意事项

  • 非 Servlet 场景下 attributes 为空,不要指望用它传 token。
  • 别把 service.loadAuthorizedClient(...) 读到的结果当成失败请求的 token。
  • 条件删除要按 registrationId/principalName 做原子操作,不要用全局大锁把所有资源请求串起来。
  • failure.getAuthorizedClient() 是 7.1.1 中 OAuth2AuthorizationFailure 已经提供的能力。如果封装了自定义 interceptor/manager,也可以在那里捕获发送时的 authorized client,但通常没必要。

备注:内容仅供参考。