SpringBoot Security 自定义异常消息

默认情况未登录和无权限都是返回403,下面我可以重写未登录和无权限的两个错误返回提示

验证为未登陆状态会进入此方法,认证错误

import com.alibaba.fastjson.JSONObject;
import com.java.core.web.vo.HttpResult;
import com.java.core.web.vo.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

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

public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

        //验证为未登陆状态会进入此方法,认证错误
        response.setContentType("application/json; charset=utf-8");
        HttpResult result = HttpResult.error(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED,"登录凭证已经失效");
        String json = JSONObject.toJSONString(result);
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();

    }
}
登陆状态下,权限不足执行该方法

import com.alibaba.fastjson.JSONObject;
import com.java.core.web.vo.HttpResult;
import com.java.core.web.vo.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

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

public class AuthenticationAccessDenied implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        //登陆状态下,权限不足执行该方法
        response.setContentType("application/json; charset=utf-8");
        HttpResult result = HttpResult.error(HttpStatus.SC_FORBIDDEN,"无访问权限");
        String json = JSONObject.toJSONString(result);
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();

    }
}

配置加上这2个

//权限自定义异常
        http.exceptionHandling().accessDeniedHandler(new AuthenticationAccessDenied()).authenticationEntryPoint(new JwtAuthenticationEntryPoint());

访问的时候就能区分了

{
  "code": 403,
  "msg": "无访问权限"
}

{
  "code": 407,
  "msg": "登录凭证已经失效"

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值