Shiro是一個用於身份驗證、授權、加密、會話管理等的Java的安全框架,為Java應用程序提供安全認證和授權支持。在實際開發過程中,除了需要進行身份驗證和授權認證外,還需要對一些請求進行不攔截處理。本文將從以下幾個方面對Shiro配置不攔截的請求做詳細的闡述。
一、配置不攔截的請求
Shiro提供了對某些請求不攔截的配置,只需要在shiro.ini或shiro.xml配置文件中進行如下配置即可:
[urls] /login.jsp = anon /logout = logout /** = authc
其中:
- “/login.jsp”:不需要身份驗證的請求,即允許匿名訪問的請求。
- “/logout”:登出請求,當用戶請求登出時,Shiro將自動清除用戶的身份信息以及相關的會話信息。
- “/**”:所有請求都需要進行身份驗證。
在Shiro中,”anon”表示匿名訪問,”logout”表示登出請求,”authc”表示身份驗證請求。
例如:
[main] ... [urls] /logout = logout /index.jsp = anon /** = authc
這個配置表示匿名訪問”/index.jsp”,清除用戶信息請求”/logout”,其他所有請求都需要進行身份驗證。
二、自定義攔截器
在Shiro中,如果默認的Filter無法滿足我們的需求,我們可以通過自定義Filter進行擴展。
步驟如下:
- 定義一個Filter類,繼承Shiro中的org.apache.shiro.web.filter.authc.FormAuthenticationFilter類,並重寫其中的onPreHandle()方法。
- 在shiro.ini或shiro.xml文件中添加Filter定義。
- 添加過濾器配置。
例如:
定義一個CustomFormAuthenticationFilter類,代碼如下:
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter { @Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { // 判斷是否為登錄請求 if (isLoginSubmission(request, response)) { // 處理登錄請求 return executeLogin(request, response); } else { // 其他請求不進行攔截 return true; } } }
在shiro.ini文件中添加以下內容:
# 添加Filter定義 [filters] customFilter = org.example.CustomFormAuthenticationFilter # 添加過濾器配置 [urls] /login = customFilter /logout = logout /** = authc
這個配置表示對”/login”請求使用自定義的CustomFormAuthenticationFilter過濾器,清除用戶信息請求”/logout”,其他所有請求都需要進行身份驗證。
三、使用註解實現不攔截
在Shiro中,我們還可以使用註解的方式來實現對某些請求的不攔截。
步驟如下:
- 在pom.xml文件中引入依賴項。
- 在shiro.ini或shiro.xml文件中進行配置。
- 在Controller中使用@RequiresPermissions註解標註不攔截的請求。
例如:
在pom.xml文件中添加Shiro-annotations依賴:
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-annotations</artifactId> <version>1.2.5</version> </dependency>
在shiro.ini文件中添加以下內容:
# 開啟註解支持 [main] shiro.annotations.enabled = true # 添加過濾器配置 [urls] /logout = logout /** = authc
在Controller中使用@RequiresPermissions註解標註不攔截的請求:
@Controller public class UserController { /** * 不需要進行身份驗證的請求 */ @RequestMapping("/index") @RequiresPermissions(value = "index:view", logical = Logical.OR) public String index() { return "index"; } /** * 需要進行身份驗證的請求 */ @RequestMapping("/user/list") @RequiresPermissions(value = "user:view", logical = Logical.OR) public String userList() { return "userList"; } }
這個配置表示對”/index”請求不進行身份驗證,對”/user/list”請求需要進行身份驗證。
四、總結
通過上述的介紹,我們可以了解如何在Shiro中配置不攔截的請求,還可以使用自定義Filter和註解的方式實現對某些請求的不攔截。這些功能的使用可以根據實際的業務需求進行選擇,有助於提高開發效率和編寫更加安全的Java應用程序。
原創文章,作者:JZMB,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/138568.html