如何处理过期的访问令牌(自定义实现返回500而不是401)

zyfwsgd6  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(313)

我有一个spring引导应用程序,它使用rest模板访问rest服务。此服务需要一个访问令牌来向您提供响应(200确定)。
如果令牌已过期而不是401,服务将返回500内部服务器错误。
因为这是一个我无法说服/要求他们返回401的系统,所以我无法使用经典的http拦截器根据响应状态获取新令牌。
获取新令牌并重试出现500个内部服务器错误的调用的最佳方法是什么?我应该用controlleradvise吗?我是新来的Spring,我有点困惑与“适当”的机制。

u4dcyp6a

u4dcyp6a1#

我建议,请检查异常类型也检查其他参数(系统错误代码,描述)在回应时,你得到一个500。如果异常类型与authenticationexception/access denied相关,则可以尝试重试机制。
简单的伪代码就是这样。

if(Http.Status_Code== 500){
           if(Exception instance of AuthenticationException){
                   //call to get the access token
                   // call the service again
                } 
            }

另外,你还要检查spring重试机制,
spring重试注解
@enableretry–在spring boot项目中启用spring retry
@retryable–指示任何方法都是重试的候选方法
@recover–指定回退方法!
https://howtodoinjava.com/spring-boot2/spring-retry-module/
https://docs.spring.io/spring-batch/docs/current/reference/html/retry.html

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.3.1</version>
</dependency>

相关问题