基于角色得后台权限管理系统设计(六、spring security 让异常返回json数据而不是页面跳转)

本文详细介绍了如何在Spring Security框架中配置自定义的异常处理机制,包括权限不足和认证失败的情况,并实现统一的JSON响应格式。通过具体代码示例,展示了如何创建和使用自定义的处理器来处理这些异常,确保系统的稳定性和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一次故意输错密码

第二次使用admin登入,然后反问user页面的getUser

 

统一定义返回

/**
 * @Auth yaozhongjie
 * @Date 2019/7/3 20:44
 **/
public class Render {
    public static void respJson(String msg,HttpServletResponse httpServletResponse){
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("utf-8");
        PrintWriter writer = null;
        try {
            writer = httpServletResponse.getWriter();
            writer.write(JSON.toJSONString(Result.error(msg),SerializerFeature.WriteMapNullValue));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.close();
        }
    }
}

Result类标准化输出。需要lombok插件

/**
 * @Auth yaozhongjie
 * @Date 2019/6/28 9:56
 **/
@Data
public class Result<T> {
    private Integer code;
    private String msg;
    private T data;


    public static Result success(String msg){
        Result result=new Result();
        result.code=0;
        result.msg=msg;
        return result;
    }

    public static Result success(JSONObject data){
        Result result=new Result();
        result.code=0;
        result.msg="success";
        result.data=data;
        return result;
    }

    public static Result error(String msg){
        Result result=new Result();
        result.code=-1;
        result.msg=msg;
        return result;
    }

}

 

添加权限异常处理

/**
 * @Auth yaozhongjie
 * @Date 2019/7/3 20:37
 **/
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        Render.respJson("无权访问",httpServletResponse);
    }
}

添加授权失败处理

/**
 * @Auth yaozhongjie
 * @Date 2019/7/3 20:43
 **/
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Render.respJson("认证失败",httpServletResponse);
    }
}

httpSecurity中配置异常处理器

    /*
    @Autowired
    MyAccessDeniedHandler accessDeniedHandler;
    @Autowired
    MyAuthenticationFailureHandler authenticationFailureHandler;

    */

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/data/*").hasRole("ADMIN")
                .mvcMatchers("/admin/*").hasRole("ADMIN")
                .mvcMatchers("/user/*").hasRole("USER")
                .anyRequest()
                .authenticated()
        ;
        //注意认证失败处理在这里配置
        http.formLogin().failureHandler(authenticationFailureHandler).permitAll();
        //权限校验失败处理在这配置
        http.exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值