如何在 Spring Boot Rest 模板客户端中处理过期的刷新令牌 [英] How to handle expiring refresh tokens in spring boot rest template client

查看:81
本文介绍了如何在 Spring Boot Rest 模板客户端中处理过期的刷新令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将第三方 API 集成到我的 Spring Boot 应用程序中.

I'm working on integrating a third party API in my spring boot application.

第三方 API 身份验证的工作原理:

How the third party API authentication works:

  1. 初始授权后,我会收到刷新令牌和在给定时间后过期的访问令牌
  2. 访问令牌过期后,我使用刷新令牌获取新的访问令牌和新的刷新令牌

使用当前的访问令牌,我可以调用 API.

With the current access token I can make calls to the API.

有没有办法使用 RestTemplate 无缝处理这种情况?

Is there a way to seamlessly handle such case using RestTemplate?

我尝试手动处理这种情况,所以如果我从 API 返回 401,我会发送一个刷新令牌请求,重写我返回的密钥并重试该请求,但不确定如何处理将 api 密钥存储在如果我需要重新启动服务器.

I've tried handling this case manually, so if I got 401 back from the API I sent a refresh token request, rewrote the keys I got back and retried the request, not really sure how to handle storing the api keys in case I need to restart the server.

推荐答案

这可以通过 ClientHttpRequestInterceptor 轻松完成,您可以在其中替换请求标头,例如401 发生:

This is easily done with a ClientHttpRequestInterceptor in which you can replace a requests header if e.g. a 401 occured:

@Override
public ClientHttpResponse intercept(
  HttpRequest request, 
  byte[] body, 
  ClientHttpRequestExecution execution) throws IOException {

    ClientHttpResponse response = execution.execute(request, body);
    if(response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
       request.getHeaders().replace("Auth-Header", getNewToken());
       return execution.execute(request, body);
    }
    return response;
}

请参阅此处以获得进一步指导.

See here for further guidance.

这篇关于如何在 Spring Boot Rest 模板客户端中处理过期的刷新令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆