springboot+shiro 跨域解决(OPTIONS)

 

拦截器判断

拦截器截取到请求先进行判断,如果是OPTIONS请求的话,则放行

import com.alibaba.fastjson.JSON;
import com.zp.demo.util.JwtHelperUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

//需要认证的API被调用前执行的拦截器也叫过滤器
public class TokenFilter extends AuthenticationFilter {

    private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
       //这几句代码是关键
            if ("OPTIONS".equals(request.getMethod())){
                response.setStatus(org.apache.http.HttpStatus.SC_NO_CONTENT);;
                logger.info("OPTIONS 放行");
                return true;
            }
            String token = getToken(servletRequest);
            //判断token 是否为空
            if (StringUtils.isEmpty(token)) {
                this.printUnauthorized("401", (HttpServletResponse) servletResponse);
                return false;
            } else {//不为空判断是否过期
                Map maps = (Map) JSON.parse(JwtHelperUtil.validateLogin(token));
                if (maps == null) {
                    logger.info("token过期返回403");
                    response.setStatus(403);//可以用response.getWriter()返回json或你想要的格式,同时设置header: Content-Type:text/json
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error("空指针异常", e);
        }
        logger.info("token有效放行");
        return true;
    }
private String getToken(ServletRequest servletRequest) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authorizationHeader = request.getHeader("Authorization");//获取请求头中的Authorization属性
        //System.out.println(authorizationHeader);
        if (!StringUtils.isEmpty(authorizationHeader)) {
            return authorizationHeader.replace(" ", "");
        }
        return null;
    }

    private void printUnauthorized(String messageCode, HttpServletResponse response) {
        String content = String.format("{\"code\":\"%s\",\"msg\":\"%s\"}", messageCode, HttpStatus.UNAUTHORIZED.getReasonPhrase());
        response.setContentType("application/json;charset=UTF-8");
        response.setContentLength(content.length());
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        try {
            PrintWriter writer = response.getWriter();
            writer.write(content);
        } catch (IOException var5) {
            var5.printStackTrace();
        }

    }
}

配置跨越:

import org.springframework.stereotype.Component;

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

/*
配置跨越访问
 */
@Component
public class AllowOriginFilter implements Filter {

    @SuppressWarnings("unused")
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*"); // 设置允许所有跨域访问
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }


}

你可能感兴趣的:(shiro)