关于使用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的方式发送所改造的响应字符串。

相关推荐
南宫生10 分钟前
力扣每日一题【算法学习day.133】
java·学习·算法·leetcode
獨枭12 分钟前
如何在 Mac 上安装并配置 JDK 环境变量
java·macos·jdk
m0_7383556924 分钟前
java泛型
java·开发语言
web2u28 分钟前
Docker入门及基本概念
java·运维·服务器·spring·docker·容器
qq_2187533138 分钟前
常用Git命令
java·git
计算机小白一个1 小时前
蓝桥杯 Java B 组之背包问题(01背包、完全背包)
java·职场和发展·蓝桥杯
计算机毕设定制辅导-无忧学长1 小时前
Maven 基础环境搭建与配置(二)
java·maven
五月茶1 小时前
Maven+SSM+SpringBoot+Mybatis-Plus
spring boot·maven·mybatis
逸狼1 小时前
【JavaEE进阶】Spring IoC
java·spring·java-ee
C#Thread1 小时前
C#上位机--进程和线程的区别
java·开发语言