遇到問題:在前後端分離跨域存取的項目中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過濾器重寫與配置的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!