日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

给zuul网关添加过滤器

發布時間:2024/4/13 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 给zuul网关添加过滤器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

網關的登錄攔截器

接下來,我們在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);@PostConstructpublic 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 {@Autowiredprivate JwtProperties properties;@Overridepublic String filterType() {return "pre";}@Overridepublic int filterOrder() {return 5;}@Overridepublic boolean shouldFilter() {return true;}@Overridepublic Object run() throws ZuulException {// 獲取上下文RequestContext context = RequestContext.getCurrentContext();// 獲取requestHttpServletRequest request = context.getRequest();// 獲取tokenString token = CookieUtils.getCookieValue(request, this.properties.getCookieName());// 校驗try {// 校驗通過什么都不做,即放行JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());} catch (Exception e) {// 校驗出現異常,返回403context.setSendZuulResponse(false);context.setResponseStatusCode(HttpStatus.FORBIDDEN.value());}return null;} }

重啟,刷新頁面,發現請求校驗的接口也被攔截了:

證明我們的攔截器生效了,但是,似乎有什么不對的。這個路徑似乎不應該被攔截啊!

總結

以上是生活随笔為你收集整理的给zuul网关添加过滤器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。