sa-token前后端分离解决跨域的正确姿势-2.正确姿势

时间:2024-07-07 18:30:48

2.1SaTokenConfigure配置如下

package xxxx.config;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import xxxx.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    // Sa-Token 整合 jwt (Simple 简单模式)
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }

    /**
     * 注册 [Sa-Token 全局过滤器]
     */
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                // 指定 [拦截路由] 与 [放行路由]
                .addInclude("/**")
                // 登录认证 -- 拦截所有路由,并排除/user/login 用于开放登录
                .addExclude("/admin/**")
                .addExclude("/favicon.ico")
                .addExclude("*.js")
                .addExclude("*.css")
                // 认证函数: 每次请求执行
                .setAuth(obj -> {
                    SaManager.getLog().debug("----- 请求path={}  提交token={}", SaHolder.getRequest().getRequestPath(), StpUtil.getTokenValue());
                    // ...
                    SaRouter.match("/**")    // 拦截的 path 列表,可以写多个 */
                            // 排除掉的 path 列表,可以写多个
                            .check(r -> StpUtil.checkLogin());// 要执行的校验动作,可以写完整的 lambda 表达式

                    // 根据路由划分模块,不同模块不同鉴权
                    //内部系统的登录权限
                    //SaRouter.match("/inner/cam/**", r -> StpUtil.checkPermission("inner.cam"));
                    //SaRouter.match("/inner/cds/**", r -> StpUtil.checkPermission("inner.cds"));
                    //SaRouter.match("/inner/cim/**", r -> StpUtil.checkPermission("inner.cim"));
                    //SaRouter.match("/inner/ads/**", r -> StpUtil.checkPermission("inner.ads"));
                    //SaRouter.match("/inner/rs/**", r -> StpUtil.checkPermission("inner.rs"));
                    //SaRouter.match("/inner/clw/**", r -> StpUtil.checkPermission("inner.clw"));

                    //外部系统登录权限
                    //SaRouter.match("/out/wb/**", r -> StpUtil.checkPermission("out.wb"));
                    //SaRouter.match("/out/cm/**", r -> StpUtil.checkPermission("out.cm"));
                    //SaRouter.match("/out/cds/**", r -> StpUtil.checkPermission("out.cds"));
                    //SaRouter.match("/out/rs/**", r -> StpUtil.checkPermission("out.rs"));
                    //SaRouter.match("/out/ads/**", r -> StpUtil.checkPermission("out.ads"));
                    // 更多拦截处理方式,请参考“路由拦截式鉴权”章节 */
                })

                // 异常处理函数:每次认证函数发生异常时执行此函数
                .setError(e1 -> {
                    log.error("sa-token异常:{}", e1.getMessage());
                    // 设置响应头
                    SaHolder.getResponse().setHeader("Content-Type", "application/json;charset=UTF-8");
                    /**
                     * sa-token登录相关异常处理
                     * https://sa-token.cc/v/v1.36.0/doc.html#/fun/exception-code
                     */
                    if (e1 instanceof SaTokenException) {
                        SaTokenException e = (SaTokenException) e1;
                        // 根据不同异常细分状态码返回不同的提示
                        if (e.getCode() == 11001) {
                            return RestResponse.fail("未能读取到有效Token");
                        }
                        if (e.getCode() == 11002) {
                            return RestResponse.fail("登录时的账号为空");
                        }
                        if (e.getCode() == 11011) {
                            return RestResponse.fail("未能读取到有效Token");
                        }
                        if (e.getCode() == 11012) {
                            return RestResponse.fail("Token无效");
                        }
                        if (e.getCode() == 11013) {
                            return RestResponse.fail("Token已过期");
                        }
                        if (e.getCode() == 11014) {
                            return RestResponse.fail("Token已被顶下线");
                        }
                        if (e.getCode() == 11015) {
                            return RestResponse.fail("Token已被踢下线");
                        }
                        if (e.getCode() == 11016) {
                            return RestResponse.fail("Token已被冻结");
                        }
                        if (e.getCode() == 11017) {
                            return RestResponse.fail("未按照指定前缀提交token");
                        }
                        if (e.getCode() == 11041) {
                            return RestResponse.fail("缺少指定的角色");
                        }
                        if (e.getCode() == 11051) {
                            return RestResponse.fail("缺少指定的权限");
                        }
                        if (e.getCode() == 11061) {
                            return RestResponse.fail("当前账号未通过服务封禁校验");
                        }
                        if (e.getCode() == 11062) {
                            return RestResponse.fail("提供要解禁的账号无效");
                        }
                        if (e.getCode() == 12001) {
                            return RestResponse.fail("请求中缺少指定的参数");
                        }
                        if (e.getCode() == 12111) {
                            return RestResponse.fail("密码md5加密异常");
                        }
                        if (e.getCode() == 30201) {
                            return RestResponse.fail("对jwt字符串解析失败");
                        }
                        if (e.getCode() == 30202) {
                            return RestResponse.fail("此jwt的签名无效");
                        }
                        if (e.getCode() == 30203) {
                            return RestResponse.fail("此jwt的loginType字段不符合预期");
                        }
                        if (e.getCode() == 30204) {
                            return RestResponse.fail("此jwt已超时");
                        }
                        if (e.getCode() == 30205) {
                            return RestResponse.fail("没有配置jwt秘钥");
                        }
                        if (e.getCode() == 30206) {
                            return RestResponse.fail("登录时提供的账号为空");
                        }
                        // 更多 code 码判断 ...
                        // 默认的提示
                        return RestResponse.fail("登录异常,请联系管理员处理...");
                    }
                    return RestResponse.fail(e1.getMessage());
                })

                // 前置函数:在每次认证函数之前执行
                .setBeforeAuth(obj -> {
                    // 获得客户端domain
                    SaRequest request = SaHolder.getRequest();
                    String origin = request.getHeader("Origin");
                    if (origin == null) {
                        origin = request.getHeader("Referer");
                    }
                    // ---------- 设置一些安全响应头 ----------
                    SaHolder.getResponse()
                            // 服务器名称
                            //.setServer("sa-server")
                            // 是否可以在iframe显示视图: DENY=不可以 | SAMEORIGIN=同域下可以 | ALLOW-FROM uri=指定域名下可以
                            .setHeader("X-Frame-Options", "SAMEORIGIN")
                            // 是否启用浏览器默认XSS防护: 0=禁用 | 1=启用 | 1; mode=block 启用, 并在检查到XSS攻击时,停止渲染页面
                            .setHeader("X-XSS-Protection", "1; mode=block")
                            // 禁用浏览器内容嗅探
                            .setHeader("X-Content-Type-Options", "nosniff")
                            // ---------- 设置跨域响应头 ----------
                            // 允许指定域访问跨域资源
                            .setHeader("Access-Control-Allow-Origin", origin)
                            // 允许所有请求方式
                            .setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT")
                            // 允许的header参数
                            .setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With,satoken")
                            .setHeader("Access-Control-Allow-Credentials", "true")
                            // 有效时间
                            .setHeader("Access-Control-Max-Age", "3600");

                    // 如果是预检请求,则立即返回到前端
                    SaRouter.match(SaHttpMethod.OPTIONS)
                            .free(r -> {
                                log.info("--------OPTIONS预检请求,不做处理,直接返回响应状态码为200");
                                SaHolder.getResponse().setStatus(HttpServletResponse.SC_OK);
                            })
                            .back();
                });
    }

}

2.2SimpleCORSFilter跨域配置如下

package com.dy.corporate.member.config;

import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SimpleCORSFilter implements Filter {

    @Override
    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-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest) req).getHeader("origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With,satoken");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

    对之前的集成sa-token实现登录和RBAC权限控制文章中的配置做一些更改和新增配置上上面这个两个类即可解决跨域问题。