关于使用SpringSecurity框架发起JSON请求,但因登陆失效导致响应403的问题。

这里记录一个生产中遇到的一个问题。

现有环境是基于SpringBoot 2.6.8,然后是前后台一体化的项目。

安全框架使用的是内置版本的SpringSecurity。

在实际使用过程中遇到一个问题。

就是当用户登陆失效后,前端操作JSON请求获取列表数据,但因为登陆失效了。导致请求过不去返回结果

同时服务端也没有任何的异常日志。

后来发现是因为Security内置的一个过滤器CsrfFilter。这个过滤器

复制代码
this.accessDeniedHandler.handle(request, response, exception);

有个处理起对这个请求进行了处理,同时转发到了error页面。

解决方案如下:

1.首先需要实现上述过滤器内调用的处理器

java 复制代码
import cn.com.seecom.vnumber.common.Result;
import cn.com.seecom.vnumber.common.ResultEnum;
import cn.com.seecom.vnumber.utils.RequestUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

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

/**
 * @author lvshiyu
 * @description: 重写当请求访问被拒绝处理
 * 在基于角色的访问控制(RBAC)或基于权限的访问控制(PBAC)系统中,当用户尝试访问他们没有权限的资源时,
 * Spring Security 会触发 AccessDeniedHandler 来处理这种情况。
 * @date 2024年03月13日 17:55
 */
@Component
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private String errorPage;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (response.isCommitted()) {
            log.trace("Did not write to response since already committed");
            return;
        }
        if (RequestUtil.isAjaxRequest(request)) {
            // 重点是这里,判断如果是ajax请求,则返回对应的登陆失效JSON。
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.getWriter().println(JSON.toJSON(new Result(ResultEnum.TOKEN_EXPIRED)));
            return;
        }
        if (this.errorPage == null) {
            log.debug("Responding with 403 status code");
            response.sendError(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase());
            return;
        }
        // Put exception into request scope (perhaps of use to a view)
        request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
        // Set the 403 status code.
        response.setStatus(HttpStatus.FORBIDDEN.value());
        // forward to error page.
        request.getRequestDispatcher(this.errorPage).forward(request, response);
    }

    public void setErrorPage(String errorPage) {
        Assert.isTrue(errorPage == null || errorPage.startsWith("/"), "errorPage must begin with '/'");
        this.errorPage = errorPage;
    }

}

2.在配置类中引入该处理器,这里涉及到部分的业务代码,所以采用截图的方式,只需要将上面的失效处理器配置到config中即可。

3.在前端JS内对发起请求的地方做统一拦截处理。

javascript 复制代码
$.ajaxSetup({
            complete: function(xhr, status) {
                if (xhr.responseText == 'invalidSession') {
                    if(window.parent){
                        window.parent.location.reload();
                    }else{
                        window.location.reload();
                    }
                }
                //优化统一AJAX拦截
                if (xhr.status == 200 && xhr.responseJSON != null) {
                    let data = xhr.responseJSON;
                    if (data.code == 1000) {
                        console.log("登陆失效")
                        //登陆超时
                        window.location.reload();
                    }
                }
            }
        });

这里就解决了上述所说的问题,如果对您有帮助 请帮忙点个赞。

注意:这里重写了原来的403异常信息,会导致原有出现403的异常都会通过JSON的方式发送所改造的响应字符串。

相关推荐
AI云原生15 小时前
在 openEuler 上使用 x86_64 环境编译 ARM64 应用的完整实践
java·运维·开发语言·jvm·开源·开源软件·开源协议
科普瑞传感仪器15 小时前
航空航天制造升级:机器人高精度力控打磨如何赋能复合材料加工?
java·前端·人工智能·机器人·无人机·制造
q_191328469515 小时前
基于SpringBoot2+Vue2的宠物上门服务在线平台
java·vue.js·spring boot·mysql·宠物·计算机毕业设计·源码分享
CoderYanger15 小时前
动态规划算法-两个数组的dp(含字符串数组):42.不相交的线
java·算法·leetcode·动态规划·1024程序员节
小蝙蝠侠15 小时前
async-profiler 火焰图宽度是否可信?哪些情况下会误导?(深度解析)
java·性能优化
IT_Octopus15 小时前
java多线程环境下 安全地初始化缓存(避免缓存击穿),同时兼顾性能 的双重检查锁方案
java·spring·缓存
Li_76953215 小时前
Spring Cloud —— SkyWalking(四)
java·spring cloud·skywalking
while(1){yan}15 小时前
多线程CAS八股文
java·开发语言·面试
zfj32115 小时前
Docker和容器OCI规范的关系
java·docker·eureka
李拾叁的摸鱼日常15 小时前
从 Java 8 升级视角看Java 17 新特性详解
java·后端