SpringBoot+Shiro跨域,四个主要问题+可能遇到的其他问题

该问题是Shiro跨域所需要面对的第一个问题。
Shiro默认会将SessionId保存到cookie中,但是跨域的情况下,要求前端自己维护一个“cookie”的不太现实.
解决思路是:登录时将SessionId以结果的方式返回给前端,然后让前段将其储存起来,并在发起需要认证的请求时,在请求header添加该SessionId(例如给header添加自定义属性token,设置值为SessionId).

后端修改默认的Shiro验证信息获取过程,从header的请求头中获取自定义属性token(也就是SessionId),交给Shiro做认证。

以上思路具体执行主要遇到两个问题
1.如何修改Shiro默认的SessionId获取方式
2.跨域配置会将自定义的header属性token过滤掉,然后报错,如何配置跨域,使自定义的header属性token不被拦截
3.跨域问题:跨域访问的OPTIONS请求通通放行
4.取消shiro的自动跳转,只以JSON格式的数据通知用户行为结果

解决
1.如何修改Shiro默认的SessionId获取方式
首先在Shiro配置中将cookie禁用掉。

    @Bean(name = "sessionManager")
    public ShiroSessionManager sessionManager(@Qualifier("sessionDAO") RedisSessionDao sessionDAO,
                                              @Qualifier("sessionIdCookie") SimpleCookie sessionIdCookie) {
        ShiroSessionManager manager = new ShiroSessionManager();
        manager.setGlobalSessionTimeout(GloableField.REDIS_TIME_OUT);
        manager.setDeleteInvalidSessions(true);
        manager.setSessionValidationSchedulerEnabled(true);
//        manager.setSessionValidationScheduler(sessionValidationScheduler);
        manager.setSessionDAO(sessionDAO);
        manager.setSessionIdCookieEnabled(false);
//        manager.setSessionIdCookieEnabled(true);
//        manager.setSessionIdCookie(sessionIdCookie);
        manager.setSessionIdUrlRewritingEnabled(false);
        return manager;
    }

然后可以开始分析如何替代从cookie中获取sessionid的默认逻辑。

Shiro的DefaultWebSessionManager有一个getSessionId(ServletRequest request, ServletResponse response)的方法,可以继承该类并重新getSessionId(ServletRequest request, ServletResponse response)方法,从header中获取自定义属性token所携带的SessionId.

首先来看DefaultWebSessionManager的getSessionId()在干什么。

protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
    //  直接调用了自己的另一个方法getReferencedSessionId()
        return this.getReferencedSessionId(request, response);
}


private Serializable getReferencedSessionId(ServletRequest request, ServletResponse response) {
        //默认从cookie中获取sessionId(印证了Shiro默认是将SessionId保存在cookie这个逻辑)
        String id = this.getSessionIdCookieValue(request, response);
        if (id != null) {
        //从cookie中获取到的id,设置到request header,key是ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,其对应的值为cookie.这个是我们需要改的            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "cookie");
        } else {
            //这里是没有从cookie中取到id的情况,重点关注
            id = this.getUriPathSegmentParamValue(request, "JSESSIONID");
            if (id == null) {
                String name = this.getSessionIdName();
                id = request.getParameter(name);
                if (id == null) {
                    id = request.getParameter(name.toLowerCase());
                }
            }

            if (id != null) {
              //取到id后要做的事情1,设置ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE
                request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "url");
            }
        }

        if (id != null) {
         //取到id后要做的事情2,给request设置如下两个参数
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
        }

        request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED, this.isSessionIdUrlRewritingEnabled());
        return id;
    }

根据源码,改造如下

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

@Slf4j
public class ShiroSessionManager extends DefaultWebSessionManager {

    /**
     * 客户端request的header中,自定义属性的名称是token(值是sessionid)
     */
    public final static String HEADER_TOKEN_NAME = "token";
  //给ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE设置的值,值可随意,但是根据之前的源码,我们不能取cookie和url等字段,取mystateless,无状态的,应该不会和源码冲突
    private static final String REFERENCED_SESSION_ID_SOURCE = "mystateless";
//    Stateless request
    /**
     * 重写getSessionId,分析请求头中的指定参数,做用户凭证sessionId
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response){
        String id = WebUtils.toHttp(request).getHeader(HEADER_TOKEN_NAME);
        if(StringUtils.isEmpty(id)){
            //如果没有携带id参数则按照默认方式获取,事实上,只有登录接口和一些不需要游客身份使用的接口以外,没有任何接口会走这个逻辑,因为我们已经没有了cookie
            //  System.out.println("super:"+super.getSessionId(request, response));
            return super.getSessionId(request, response);
        }else{
            //如果请求头中有 token ,则参照源码设置三项
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            return id;
        }
    }
}

第一个问题解决。

2.跨域配置会将自定义的header属性token过滤掉,然后报错,如何配置跨域,使自定义的header属性token不被拦截

在跨域配置中放行token字段就好。

贴出CrossFilter配置

package com.ysty.server.config;

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter implements Filter {

    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);


    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        System.err.println("CorsFilter");
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
      //跨域设置,谁来都放行,与设置成*效果相同,但是这里设置成*行不通,因此用该方法代替
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
    //不能设置成*,否则跨域请求会失败
        response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
    //我这里需要放行这三个header头部字段
        response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,token");

        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
//
//            System.err.println("CrosFilter Error start");
//            e.printStackTrace();
//            System.err.println("CrosFilter Error end");
//            if((e.getCause()+"").contains("UnauthorizedException")){
//            }
        }
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}

3.跨域问题:跨域访问的OPTIONS请求通通放行
跨域请求有一个前置请求,method类型OPTIONS。该请求会被shiro拦截,故而应该统统放行。

继承BasicHttpAuthenticationFilter,然后重写preHandler方法,最后,在Shiro配置添加到过滤器链,key为authc(过滤器链添加到ShiroFilterFactoryBean中)

@Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
      //无条件放行OPTIONS
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            setHeader(httpRequest, httpResponse);
            return true;
        }
        return super.preHandle(request, response);
    }

    /**
     * 为response设置header,实现跨域
     */
    private void setHeader(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("ShiroFilter");
//        System.err.println("setHeader -- " + request.getHeader("Access-Control-Request-Headers"));
        //跨域的header设置
//        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
//        response.setHeader("Access-Control-Allow-Methods", request.getMethod());
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,token");
//        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Allow-Headers") + ",token");
        //防止乱码,适用于传输JSON数据
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
    }

未完待续...

你可能感兴趣的:(SpringBoot+Shiro跨域,四个主要问题+可能遇到的其他问题)