SpringCloud笔记之Zuul过滤器PreFilter实现token校验(简单样例)
程序员文章站
2022-06-28 18:31:42
1、首先准备访问路径,请求传递参数tokenhttp://localhost/v2/customer/version?token=1232、创建AuthenticationFilter@Componentpublic class AuthenticationFilter extends ZuulFilter{ @Override public String filterType() { return FilterConstants.PRE_TYPE; }...
1、首先准备访问路径,请求传递参数token
http://localhost/v2/customer/version?token=123
2、创建AuthenticationFilter
@Component
public class AuthenticationFilter extends ZuulFilter{
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return PRE_DECORTION_FILTER_ORDER -2;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
// 在run方法中编写具体的业务逻辑
//1. 获取Request对象
RequestContext requestContext=RequestContext.getCurrentContext();
HttpServletRequest request=requestContext.getRequest();
//2. 获取token参数
String token=request.getParamter("token");
//3. 对比token
if(token==null||!"123".equalsIgnoreCase(token)){
//4. token校验失败,直接响应数据
requestContext.setSendZuulResponse(false);
requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
}
return null;
}
}
本文地址:https://blog.csdn.net/weixin_46897235/article/details/107369457