给zuul网关添加过滤器
程序员文章站
2022-05-19 10:11:07
...
网关的登录拦截器
接下来,我们在Zuul编写拦截器,对用户的token进行校验,如果发现未登录,则进行拦截。
引入jwt相关配置
既然是登录拦截,一定是前置拦截器,我们在leyou-gateway
中定义。
首先在pom.xml中,引入所需要的依赖:
<dependency>
<groupId>com.learn.common</groupId>
<artifactId>learn-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.learn.auth</groupId>
<artifactId>learn-auth-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
然后编写application.yml属性文件,添加如下内容:
learn:
jwt:
pubKeyPath: C:\\tmp\\rsa\\rsa.pub # 公钥地址
cookieName: LY_TOKEN # cookie的名称
编写属性类,读取公钥:
@ConfigurationProperties(prefix = "learn.jwt")
public class JwtProperties {
private String pubKeyPath;// 公钥
private PublicKey publicKey; // 公钥
private String cookieName;
private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);
@PostConstruct
public void init(){
try {
// 获取公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
} catch (Exception e) {
logger.error("初始化公钥失败!", e);
throw new RuntimeException();
}
}
public String getPubKeyPath() {
return pubKeyPath;
}
public void setPubKeyPath(String pubKeyPath) {
this.pubKeyPath = pubKeyPath;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
public String getCookieName() {
return cookieName;
}
public void setCookieName(String cookieName) {
this.cookieName = cookieName;
}
}
编写过滤器逻辑
基本逻辑:
-
获取cookie中的token
-
通过JWT对token进行校验
-
通过:则放行;不通过:则重定向到登录页
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginFilter extends ZuulFilter {
@Autowired
private JwtProperties properties;
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 5;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
// 获取上下文
RequestContext context = RequestContext.getCurrentContext();
// 获取request
HttpServletRequest request = context.getRequest();
// 获取token
String token = CookieUtils.getCookieValue(request, this.properties.getCookieName());
// 校验
try {
// 校验通过什么都不做,即放行
JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());
} catch (Exception e) {
// 校验出现异常,返回403
context.setSendZuulResponse(false);
context.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
}
return null;
}
}
重启,刷新页面,发现请求校验的接口也被拦截了:
证明我们的拦截器生效了,但是,似乎有什么不对的。这个路径似乎不应该被拦截啊!
上一篇: 完成登陆接口
下一篇: Mariadb数据库创建用户并且授权