您好,登錄后才能下訂單哦!
本篇內容介紹了“SpringBoot中shiro過濾器重寫與配置的方法”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
遇到問題:在前后端分離跨域訪問的項目中shiro進行權限攔截失效 (即使有正確權限的訪問也會被攔截) 時造成302重定向錯誤等問題
報錯:Response for preflight is invalid (redirect)
1.302原因:使用ajax訪問后端項目時無法識別重定向操作
2.shiro攔截失效原因:跨域訪問時有一種帶預檢訪問的跨域,即訪問時先發出一條methods為OPTIONS的的訪問,這種訪問不帶cookie等信息。造成shiro誤判斷為無權限訪問。
3.一般使用的訪問methods都是:get,post,put,delete
1.讓shiro不對預檢訪問攔截
2. 改變shiro中無權限,未登錄攔截的重定向,這就需要重寫幾個過濾器
3. 將重寫的過濾器進行配置
過濾器運行機制:
(1)shiro是否攔截訪問 以 isAccessAllowed返回值為準
(2)如果isAccessAllowed 方法返回false會進入onAccessDenied方法重定向至 登錄 or 無權限 頁面
package com.yaoxx.base.shiro; import java.io.PrintWriter; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.apache.shiro.web.util.WebUtils; import org.springframework.http.HttpStatus; /** * * @version: 1.0 * @since: JDK 1.8.0_91 * @Description: * 未登錄過濾器,重寫方法為【跨域的預檢訪問】放行 */ public class MyAuthenticationFilter extends FormAuthenticationFilter { @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { boolean allowed = super.isAccessAllowed(request, response, mappedValue); if (!allowed) { // 判斷請求是否是options請求 String method = WebUtils.toHttp(request).getMethod(); if (StringUtils.equalsIgnoreCase("OPTIONS", method)) { return true; } } return allowed; } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { if (isLoginRequest(request, response)) { // 判斷是否登錄 if (isLoginSubmission(request, response)) { // 判斷是否為post訪問 return executeLogin(request, response); } else { // sessionID已經注冊,但是并沒有使用post方式提交 return true; } } else { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; /* * 跨域訪問有時會先發起一條不帶token,不帶cookie的訪問。 * 這就需要我們抓取這條訪問,然后給他通過,否則只要是跨域的訪問都會因為未登錄或缺少權限而被攔截 * (如果重寫了isAccessAllowed,就無需下面的判斷) */ // if (req.getMethod().equals(RequestMethod.OPTIONS.name())) { // resp.setStatus(HttpStatus.OK.value()); // return true; // } /* * 跨域的第二次請求就是普通情況的request了,在這對他進行攔截 */ String ajaxHeader = req.getHeader(CustomSessionManager.AUTHORIZATION); if (StringUtils.isNotBlank(ajaxHeader)) { // 前端Ajax請求,則不會重定向 resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); resp.setHeader("Access-Control-Allow-Credentials", "true"); resp.setContentType("application/json; charset=utf-8"); resp.setCharacterEncoding("UTF-8"); resp.setStatus(HttpStatus.UNAUTHORIZED.value());//設置未登錄狀態碼 PrintWriter out = resp.getWriter(); // Map<String, String> result = new HashMap<>(); // result.put("MESSAGE", "未登錄用戶"); String result = "{"MESSAGE":"未登錄用戶"}"; out.println(result); out.flush(); out.close(); } else { // == 如果是普通訪問重定向至shiro配置的登錄頁面 == // saveRequestAndRedirectToLogin(request, response); } } return false; } }
package com.yaoxx.base.shiro; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter; import org.apache.shiro.web.util.WebUtils; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMethod; /** * * @author: yao_x_x * @since: JDK 1.8.0_91 * @Description: role的過濾器 */ public class MyAuthorizationFilter extends RolesAuthorizationFilter { @Override public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { boolean allowed =super.isAccessAllowed(request, response, mappedValue); if (!allowed) { String method = WebUtils.toHttp(request).getMethod(); if (StringUtils.equalsIgnoreCase("OPTIONS", method)) { return true; } } return allowed; } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (req.getMethod().equals(RequestMethod.OPTIONS.name())) { resp.setStatus(HttpStatus.OK.value()); return true; } // 前端Ajax請求時requestHeader里面帶一些參數,用于判斷是否是前端的請求 String ajaxHeader = req.getHeader(CustomSessionManager.AUTHORIZATION); if (StringUtils.isNotBlank(ajaxHeader)) { // 前端Ajax請求,則不會重定向 resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); resp.setHeader("Access-Control-Allow-Credentials", "true"); resp.setContentType("application/json; charset=utf-8"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); String result = "{"MESSAGE":"角色,權限不足"}"; out.println(result); out.flush(); out.close(); return false; } return super.onAccessDenied(request, response); } }
@Configuration public class ShiroConfiguration { @Autowired private RoleService roleService; @Autowired private PermissionService permissionService; @Bean("shiroFilter") public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager")SecurityManager manager) { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(manager); /* 自定義filter注冊 */ Map<String, Filter> filters = bean.getFilters(); filters.put("authc", new MyAuthenticationFilter()); filters.put("roles", new MyAuthorizationFilter()); Map<String, String> filterChainDefinitionMap =new LinkedHashMap<>(); filterChainDefinitionMap.put("/login", "anon"); // filterChainDefinitionMap.put("/*", "authc"); // filterChainDefinitionMap.put("/admin", "authc,roles[ADMIN]"); bean.setFilterChainDefinitionMap(filterChainDefinitionMap); return bean; }
“SpringBoot中shiro過濾器重寫與配置的方法”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。