spring security前后端分离Demo

本文作者通过亲身体验,分享了Spring Security在前后端分离项目中的应用,详细讲解了处理无权限、未登录授权、登录失败、登录成功、注销成功、登录拦截器、用户信息处理、验证码异常等问题,以及Spring Security的配置实践。
摘要由CSDN通过智能技术生成

总结

先上自己的总结:如果自己学习spring security,学习成本太高了。本菜鸡学了一个星期才弄明白一丢丢,一开始看大佬的博客,虽然能看懂,但是很多东西都不理解为什么这么做。只有自己去写一个demo(花费了好几天),才能彻底能清楚。

1、处理没有权限

/**
 * 处理没有权限
 */
@Component
public class CustomizeAccessDeniedHandler implements AccessDeniedHandler {
   
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
   
        Result result = new Result().error(ResultCode.NO_PERMISSION);
        httpServletResponse.setContentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE);
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}

2、处理未登录授权

/**
 * 处理未登录授权
 */
@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {
   
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
   
        Result result = new Result().error(ResultCode.NO_PERMISSION);
        result.setMsg("未授权,请先登录");
        httpServletResponse.setContentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE);
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}

3、处理登录失败错误

/**
 * 处理登录失败各种错误
 */
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {
   
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
   
        HashMap<Class<? extends Exception>, Result> map = new HashMap<Class<? extends Exception>, Result>() {
   {
   
            put(AccountExpiredException.class, new Result().error(ResultCode.USER_ACCOUNT_EXPIRED)); //账号过期
            put(BadCredentialsException.class, new Result().error(ResultCode.USER_CREDENTIALS_ERROR)); //密码错误
            put(CredentialsExpiredException.class, new Result().error(ResultCode.USER_CREDENTIALS_EXPIRED)); //密码过期
            put(DisabledException.class
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值