当前位置:网站首页>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;
}
边栏推荐
- 公司視頻加速播放
- [Thesis code] SML part code reading
- Eigen sparse matrix operation
- Interface test: what are the components of the URL in fiddler
- Usage of test macro of GTEST
- B - The Suspects
- Expose the serial fraudster Liu Qing in the currency circle, and default hundreds of millions of Cheng Laolai
- 二维码的前世今生 与 六大测试点梳理
- Idea new UI usage
- How to recover Huawei router's forgotten password
猜你喜欢
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
【微信小程序】搭建开发工具环境
LeetCode 1200. 最小绝对差
JDBC Requset 对应内容及功能介绍
(5) Explanation of yolo-v3 core source code (3)
GTSAM中李群的运用
The latest 2022 review of "graph classification research"
Detailed explanation of P problem, NP problem, NPC problem and NP hard problem
[postman] the monitors monitoring API can run periodically
把el-tree选中的数组转换为数组对象
随机推荐
LeetCode 729. 我的日程安排表 I
Thoughts on data security (Reprint)
[postman] dynamic variable (also known as mock function)
还在为如何编写Web自动化测试用例而烦恼嘛?资深测试工程师手把手教你Selenium 测试用例编写
【微信小程序】搭建开发工具环境
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Buuctf-[gxyctf2019] no dolls (xiaoyute detailed explanation)
【LeetCode】Day96-第一个唯一字符&赎金信&字母异位词
Bit operation rules
Summary of anomaly detection methods
JWT-JSON WEB TOKEN
Luogu p1460 [usaco2.1] healthy Holstein cows
PAT(乙级)2022年夏季考试
全链路压测:构建三大模型
nodejs实现微博第三方登录
Function of contenttype
Buuctf-[[gwctf 2019] I have a database (xiaoyute detailed explanation)
技术分享 | 常见接口协议解析
Interface test: what are the components of the URL in fiddler
Idea new UI usage