SpringBoot集成SpringSecurity(十四、关闭默认登录页)

本文介绍了在SpringBoot集成SpringSecurity时,如何在前后端完全分离的场景下关闭默认登录页面。通过创建自定义的授权异常处理器,处理未登录情况,并在SpringSecurity配置中关闭csrf,确保可以通过postman等工具进行登录操作。验证过程显示,未登录访问特定接口会返回未登录提示。

前言

用户在未登录的时候,访问后端服务,默认会跳转到默认登录页,这种情况在前后未分离,或者说半分离的情况下是没有问题的,但是在前后端完全分离的情况,像现在比较流行的vue.js,前后端分开部署,如果在用户未登录情况下访问后端,返回默认的登录显然是不行。下面通过配置,在用户未登录情况下访问后端时,返回之前封装的统一结果,然后前端通过状态码进行判断,跳转到自定义登录页。

实现

创建一个授权异常处理器类AuthenticationExceptionHandler并实现AuthenticationEntryPoint接口,如果是InsufficientAuthenticationException类型,那么说用户未登录,响应未登录提示。

@Component
public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws
            IOException {
        Result error = Result.error();
        if (e instanceof InsufficientAuthenticationException) {
            error.message(ResultCode.NOT_SIGN_IN.getMessage());
        }
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JsonUtil.toJsonString(error));
    }
}

SpringSecurityConfig中添加设置AuthenticationExceptionHandler
1.注入当前处理器

    @Autowired
    AuthenticationExceptionHandler authenticationExceptionHandler;

2.添加配置

http.exceptionHandling()
	.authenticationEntryPoint(authenticationExceptionHandler);

3.关闭csrf(已经没有默认登录页了,通过postman等工具进行登录,所以需要将csrf关闭)

http.csrf().disable();

验证

访问后端接口,成功返回未登录提示
在这里插入图片描述
postman模拟登录
在这里插入图片描述
访问localhost:8080/sys/user/list 访问成功
在这里插入图片描述
访问localhost:8080/sys/user/query 没有权限
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值