当前位置:网站首页>Resttemplate and feign realize token transmission
Resttemplate and feign realize token transmission
2022-07-06 06:14:00 【Snow peak expensive】
List of articles
Fegin The way
Client and server
One 、 Plus dependence
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Two 、 Definition notes
public @interface CheckLogin {
}
3、 ... and 、 Define facets
import com.itmuch.contentcenter.util.JwtOperator;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Aspect // Cut notes
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CheckLoginAspect {
private final JwtOperator jwtOperator;
//AOP Of Advice(before,after returning,after throwing,around) One of them
@Around("@annotation(com.itmuch.contentcenter.auth.CheckLogin)")// added @CheckLogin All the methods will come here
public Object checkLogin(ProceedingJoinPoint point) throws Throwable {
checkToken();
return point.proceed();
}
private void checkToken() {
try {
// 1. from header Get in there token
HttpServletRequest request = getHttpServletRequest();
String token = request.getHeader("X-Token");
// 2. check token Is it legal & Is it overdue ; If it is illegal or expired, throw the exception directly ; If it is released legally
Boolean isValid = jwtOperator.validateToken(token);
if (!isValid) {
throw new SecurityException("Token illegal !");
}
// 3. If the verification is successful , Then set the user's information to request Of attribute Inside
Claims claims = jwtOperator.getClaimsFromToken(token);
request.setAttribute("id", claims.get("id"));
request.setAttribute("wxNickname", claims.get("wxNickname"));
request.setAttribute("role", claims.get("role"));
} catch (Throwable throwable) {
throw new SecurityException("Token illegal ");
}
}
private HttpServletRequest getHttpServletRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
return attributes.getRequest();
}
}
Four 、 Client creation Fegin Interceptor
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class TokenRelayRequestIntecepor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// 1. from header Get in there token
HttpServletRequest request = getHttpServletRequest();
String token = request.getHeader("X-Token");
if(!StringUtils.isEmpty(token)){
requestTemplate.header("X-Token",token);
}
}
private HttpServletRequest getHttpServletRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
return attributes.getRequest();
}
}
Four 、 Client plus configuration
feign:
client:
config:
default: # overall situation
loggerLevel: full
requestInterceptors:
- com.itmuch.contentcenter.feignclient.interceptor.TokenRelayRequestIntecepor
5、 ... and 、 test
Incoming client token,token Will pass Fegin Interceptor handle token add .
all Fegin All interfaces will be brought token
RestTemplate The way
1. establish RestTemplate Interceptor
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class RestTemplateRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("X-Token");
HttpHeaders headers = httpRequest.getHeaders();
headers.add("X-Token", token);
// Ensure that the request continues
return clientHttpRequestExecution.execute(httpRequest, body);
}
}
2.RestTemplate example
@Bean
@LoadBalanced
@SentinelRestTemplate(
blockHandler = "handleBlock",
fallback = "handleFallback",
fallbackClass = SentinelBlockHandler.class,
blockHandlerClass = SentinelBlockHandler.class)
public RestTemplate restTemplate(){
// Add the configured interceptor to the instance
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(
Collections.singletonList(new RestTemplateRequestInterceptor())
);
return restTemplate;
}
边栏推荐
- 【Postman】Collections-运行配置之导入数据文件
- How to use the container reflection method encapsulated by thinkphp5.1 in business code
- 误差的基本知识
- 【Postman】测试(Tests)脚本编写和断言详解
- 【C语言】qsort函数
- About PHP startup, mongodb cannot find the specified module
- Software test interview questions - Test Type
- Understanding of processes and threads
- 曼哈顿距离和-打印菱形
- JMeter做接口测试,如何提取登录Cookie
猜你喜欢
H3C V7 switch configuration IRF
10m25dcf484c8g (FPGA) amy-6m-0002 BGA GPS module
数据库隔离级别
Configuring OSPF GR features for Huawei devices
(5) Explanation of yolo-v3 core source code (3)
[postman] test script writing and assertion details
P问题、NP问题、NPC问题、NP-hard问题详解
【Postman】Collections-运行配置之导入数据文件
Arrays and collections
Pat (Grade B) 2022 summer exam
随机推荐
[wechat applet] build a development tool environment
How to recover Huawei router's forgotten password
假设检验学习笔记
Detailed explanation of BF and KMP
曼哈顿距离和-打印菱形
联合索引的左匹配原则
Postman核心功能解析-参数化和测试报告
CoordinatorLayout+NestedScrollView+RecyclerView 上拉底部显示不全
在线问题与离线问题
[leetcode] day96 - the first unique character & ransom letter & letter ectopic word
IDEA 新UI使用
Embedded point test of app
黑猫带你学UFS协议第4篇:UFS协议栈详解
LeetCode 739. 每日温度
[course notes] Compilation Principle
Web界面元素的测试
Summary of anomaly detection methods
Application du Groupe Li dans gtsam
Luogu p1460 [usaco2.1] healthy Holstein cows
Cannot create PoolableConnectionFactory (Could not create connection to database server. 错误