基于Spring-Security自定义登陆错误提示信息

 更新时间:2021年12月20日 10:29:09   作者:doinbb  
这篇文章主要介绍了Spring-Security自定义登陆错误提示信息,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

实现效果如图所示:

首先公布实现代码:

一. 自定义实现

import.org.springframework.security.core.userdetails.UserDetailsService类

并且抛出BadCredentialsException异常,否则页面无法获取到错误信息。

 
@Slf4j
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService { 
    @Autowired
    private PasswordEncoder passwordEncoder; 
    @Autowired
    private UserService userService; 
    @Autowired
    private PermissionService permissionService; 
    private String passwordParameter = "password"; 
    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        HttpServletRequest request = ContextHolderUtils.getRequest();
        String password = request.getParameter(passwordParameter);
        log.error("password = {}", password);
 
        SysUser sysUser = userService.getByUsername(username);
        if (null == sysUser) {
            log.error("用户{}不存在", username);
            throw new BadCredentialsException("帐号不存在,请重新输入");
        }
        // 自定义业务逻辑校验
        if ("userli".equals(sysUser.getUsername())) {
            throw new BadCredentialsException("您的帐号有违规记录,无法登录!");
        }
        // 自定义密码验证
        if (!password.equals(sysUser.getPassword())){
            throw new BadCredentialsException("密码错误,请重新输入");
        }
        List<SysPermission> permissionList = permissionService.findByUserId(sysUser.getId());
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissionList)) {
            for (SysPermission sysPermission : permissionList) {
                authorityList.add(new SimpleGrantedAuthority(sysPermission.getCode()));
            }
        }
 
        User myUser = new User(sysUser.getUsername(), passwordEncoder.encode(sysUser.getPassword()), authorityList); 
        log.info("登录成功!用户: {}", myUser); 
        return myUser;
    }
}

二. 实现自定义登陆页面

前提是,你们已经解决了自定义登陆页面配置的问题,这里不做讨论。

通过 thymeleaf 表达式获取错误信息(我们选择thymeleaf模板引擎)

<p style="color: red" th:if="${param.error}"   th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.message}"></p>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>XX相亲网</title>
    <meta name="description" content="Ela Admin - HTML5 Admin Template">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body class="mui-content">
<div id="d1">
    <div class="first">
        <img class="hosp" th:src="@{/images/dashboard/hospital.png}"/>
        <div class="hospital">XX相亲网</div>
    </div>
    <div class="sufee-login d-flex align-content-center flex-wrap">
        <div class="container">
            <div class="login-content">
                <div class="login-logo">
                    <h1 style="color: #385978;font-size: 24px">XX相亲网</h1>
                    <h1 style="color: #385978;font-size: 24px">登录</h1>
                </div>
                <div class="login-form">
                    <form th:action="@{/login}" method="post">
                        <div class="form-group">
                            <input type="text" class="form-control" name="username" placeholder="请输入帐号">
                        </div>
                        <div class="form-group">
                            <input type="password" class="form-control" name="password" placeholder="请输入密码">
                        </div>
                        <div>
                            <button type="submit" class="button-style">
                                <span class="in">登录</span>
                            </button>
                        </div>
                        <p style="color: red" th:if="${param.error}"             
                           th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.message}">
                        </p>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Spring-Security登陆表单提交过程

当用户从登录页提交账号密码的时候,首先由

org.springframework.security.web.authentication包下的UsernamePasswordAuthenticationFilter类attemptAuthentication()

方法来处理登陆逻辑。

 
	public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {
		if (postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException(
					"Authentication method not supported: " + request.getMethod());
		} 

		String username = obtainUsername(request);
		String password = obtainPassword(request); 
		if (username == null) {
			username = "";
		}
 
		if (password == null) {
			password = "";
		}
 
		username = username.trim(); 
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
				username, password); 
		// Allow subclasses to set the "details" property
		setDetails(request, authRequest); 
		return this.getAuthenticationManager().authenticate(authRequest);
	}

1. 该类内部默认的登录请求url是"/login",并且只允许POST方式的请求。

2. obtainUsername()方法参数名为"username"和"password"从HttpServletRequest中获取用户名和密码(由此可以找到突破口,我们可以在自定义实现的loadUserByUsername方法中获取到提交的账号和密码,进而检查正则性)。

3. 通过构造方法UsernamePasswordAuthenticationToken,将用户名和密码分别赋值给principal和credentials。

    public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
        super((Collection)null);
        this.principal = principal;
        this.credentials = credentials;
        this.setAuthenticated(false);
    }

super(null)调用的是父类的构造方法,传入的是权限集合,因为目前还没有认证通过,所以不知道有什么权限信息,这里设置为null,然后将用户名和密码分别赋值给principal和credentials,同样因为此时还未进行身份认证,所以setAuthenticated(false)。

到此为止,用户提交的表单信息已加载完成,继续往下则是校验表单提交的账号和密码是否正确。

那么异常一下是如何传递给前端的呢

前面提到用户登录验证的过滤器是UsernamePasswordAuthenticationFilter,它继承自AbstractAuthenticationProcessingFilter。

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException { 
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
 
		if (!requiresAuthentication(request, response)) {
			chain.doFilter(request, response); 
			return;
		}
 
		if (logger.isDebugEnabled()) {
			logger.debug("Request is to process authentication");
		}
 
		Authentication authResult; 
		try {
			authResult = attemptAuthentication(request, response);
			if (authResult == null) {
				// return immediately as subclass has indicated that it hasn't completed
				// authentication
				return;
			}
			sessionStrategy.onAuthentication(authResult, request, response);
		}
		catch (InternalAuthenticationServiceException failed) {
			logger.error(
					"An internal error occurred while trying to authenticate the user.",
					failed);
			unsuccessfulAuthentication(request, response, failed); 
			return;
		}
		catch (AuthenticationException failed) {
			// Authentication failed
			unsuccessfulAuthentication(request, response, failed); 
			return;
		}
 
		// Authentication success
		if (continueChainBeforeSuccessfulAuthentication) {
			chain.doFilter(request, response);
		} 
		successfulAuthentication(request, response, chain, authResult);
	}

从代码片段中看到Spring将异常捕获后交给了unsuccessfulAuthentication这个方法来处理。

unsuccessfulAuthentication又交给了failureHandler(AuthenticationFailureHandler)来处理,然后追踪failureHandler

	protected void unsuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException failed)
			throws IOException, ServletException {
		SecurityContextHolder.clearContext();
 
		if (logger.isDebugEnabled()) {
			logger.debug("Authentication request failed: " + failed.toString(), failed);
			logger.debug("Updated SecurityContextHolder to contain null Authentication");
			logger.debug("Delegating to authentication failure handler " + failureHandler);
		}
 
		rememberMeServices.loginFail(request, response); 
		failureHandler.onAuthenticationFailure(request, response, failed);
	}

Ctrl + 左键 追踪failureHandler引用的类是,SimpleUrlAuthenticationFailureHandler。

	private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
	private AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();

找到SimpleUrlAuthenticationFailureHandler类中的,onAuthenticationFailure()方法。

	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
 
		if (defaultFailureUrl == null) {
			logger.debug("No failure URL set, sending 401 Unauthorized error");
 
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
					"Authentication Failed: " + exception.getMessage());
		}
		else {
			saveException(request, exception);
 
			if (forwardToDestination) {
				logger.debug("Forwarding to " + defaultFailureUrl);
 
				request.getRequestDispatcher(defaultFailureUrl)
						.forward(request, response);
			}
			else {
				logger.debug("Redirecting to " + defaultFailureUrl);
				redirectStrategy.sendRedirect(request, response, defaultFailureUrl);
			}
		}
	}

追踪到saveException(request, exception)的内部实现。

	protected final void saveException(HttpServletRequest request,
			AuthenticationException exception) {
		if (forwardToDestination) {
			request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
		}
		else {
			HttpSession session = request.getSession(false);
 
			if (session != null || allowSessionCreation) {
				request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,
						exception);
			}
		}
	}

此处的

request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); 

就是存储到session中的错误信息,key就是

public static final String AUTHENTICATION_EXCEPTION =
"SPRING_SECURITY_LAST_EXCEPTION";

因此我们通过thymeleaf模板引擎的表达式可获得session的信息。

获取方式

<p style="color: red" th:if="${param.error}" 
th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.message}">
</p>

需要注意:saveException保存的是Session对象所以需要使用${SPRING_SECURITY_LAST_EXCEPTION.message}获取。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Spring Cloud Zuul添加过滤器过程解析

    Spring Cloud Zuul添加过滤器过程解析

    这篇文章主要介绍了Spring Cloud Zuul添加过滤器过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • 浅析SpringBoot自动化配置原理实现

    浅析SpringBoot自动化配置原理实现

    这篇文章主要介绍了浅析SpringBoot自动化配置原理实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • SpringBoot整合MQTT小结汇总

    SpringBoot整合MQTT小结汇总

    MQTT 客户端是运行 MQTT 库并通过网络连接到 MQTT 代理的任何设备,是一种基于发布/订阅(publish/subscribe)模式的“轻量级”通讯协议,该协议构建于 TCP/IP 协议上,由 IBM 于 1999 年发明,对SpringBoot整合MQTT相关知识感兴趣的朋友一起看看吧
    2022-01-01
  • Java this、final等关键字总结

    Java this、final等关键字总结

    这篇文章主要对java中this、final等关键字进行了总结,需要的朋友可以参考下
    2017-04-04
  • Android 资源 id详解及的动态获取

    Android 资源 id详解及的动态获取

    这篇文章主要介绍了Android 资源 id详解及的动态获取的相关资料,需要的朋友可以参考下
    2016-12-12
  • java向文件中追加内容与读写文件内容源码实例代码

    java向文件中追加内容与读写文件内容源码实例代码

    这篇文章主要介绍了java向文件中追加内容与读写文件内容源码实例代码的相关资料,需要的朋友可以参考下
    2017-04-04
  • 全面分析Java文件上传

    全面分析Java文件上传

    本片文章给大家详细分析了Java文件上传的相关知识点,以及相关代码做了详细分析,有兴趣的朋友学习下。
    2018-02-02
  • Java HashMap实现原理分析(一)

    Java HashMap实现原理分析(一)

    这篇文章主要介绍了Java HashMap实现原理的分析,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2020-08-08
  • Spring Boot实现分布式系统中的服务发现和注册(最新推荐)

    Spring Boot实现分布式系统中的服务发现和注册(最新推荐)

    在本文中,我们深入探讨了Spring Boot如何实现分布式系统中的服务发现和注册,我们使用Eureka作为服务注册中心,Ribbon作为负载均衡器,Hystrix作为熔断器,成功地实现了服务发现、服务注册、负载均衡和服务熔断等功能,需要的朋友参考下吧
    2023-06-06
  • 详解Mybatis中的CRUD

    详解Mybatis中的CRUD

    这篇文章主要介绍了Mybatis中的CRUD的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03

最新评论