Spring Security教程(7)---- 解决UsernameNotFoundException无法被捕获的问题

这个教程是我在往项目中一点一点添加 Spring Security的过程的一个笔记,也是我学习 Spring Security的一个过程。

在解决这个问题之前要先说一点authentication-provider默认加载的是DaoAuthenticationProvider类。

完成了上一章的内容后在测试的时候发现在UserDetailsService中抛出的UsernameNotFoundException无法被捕获。于是找到DaoAuthenticationProvider,源码看了好几遍没有看出端倪。然后直接查看最顶级的接口AuthenticationProvider。发现它只有一个方法如下

Authentication authenticate(Authentication authentication) throws AuthenticationException;
抛出AuthenticationException异常,而UsernameNotFoundException是AuthenticationException的子类,那问题应该就出在authenticate这个方法上了。

然后找到DaoAuthenticationProvider的父类AbstractUserDetailsAuthenticationProvider的authenticate方法,发现了这段代码。

            try {
                user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
            } catch (UsernameNotFoundException notFound) {
                logger.debug("User '" + username + "' not found");

                if (hideUserNotFoundExceptions) {
                    throw new BadCredentialsException(messages.getMessage(
                            "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                } else {
                    throw notFound;
                }
            }
它这里有个hideUserNotFoundExceptions属性,默认是true。这样的话即便我们抛出了UsernameNotFoundException它也会转为BadCredentialsException,所以我们需要将hideUserNotFoundExceptions属性的值设为false,而在上一章中的那种配置方法是没有办法为其属性赋值的所以我们要手动注入.authentication-provider,所以配置就变成了下面的内容

	<sec:authentication-manager>
		<sec:authentication-provider ref="authenticationProvider" />
	</sec:authentication-manager>
	
	<bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
		<property name="hideUserNotFoundExceptions" value="false" />
		<property name="userDetailsService" ref="userDetailService" />
		<property name="userCache" ref="userCache" />
		<property name="messageSource" ref="messageSource" />
		<property name="passwordEncoder" ref="passwordEncode" />
		<property name="saltSource" ref="saltSource" />
	</bean>
	
	
	<!-- 配置密码加密类 -->
	<bean id="passwordEncode" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
	<bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
		<property name="userPropertyToUse" value="username"/>
	</bean>

注意:如果在authentication-provider配置中用ref指定AuthenticationProvider则authentication-provider的子元素将都不可以用。

即下面的这种配置是错误的

	<sec:authentication-manager>
		<sec:authentication-provider ref="authenticationProvider" >
			<sec:password-encoder ref="passwordEncode">
				<sec:salt-source user-property="username"/>
			</sec:password-encoder>
		</sec:authentication-provider>
	</sec:authentication-manager>
所以我们的盐值加密就需要注入到AuthenticationProvider中了。

SaltSource是一个接口有两个实现类SystemWideSaltSource和ReflectionSaltSource。

SystemWideSaltSource :只能指定固定值

ReflectionSaltSource:可以指定UserDetails的属性,这里我们用的就是它

这样的话就可以保证在抛出UsernameNotFoundException时,前台能显示出来错误信息,如下所示。


在上一章中忘了介绍如何在前台显示登录是的异常信息,在这里补上。

UsernamePasswordAuthenticationFilter认证失败后,异常信息会写到Session中,key为SPRING_SECURITY_LAST_EXCEPTION

可以通过El表达式来获取到异常的信息。

${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}


  • 20
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
Spring Security 是一个开源的安全框架,用于保护基于Spring框架构建的应用程序。MyBatis-Plus 是基于 MyBatis 的增强工具,用于简化 MyBatis 操作和提高开发效率。 将 Spring Security 与 MyBatis-Plus 整合主要包括以下几个步骤: 1. 首先,在 Spring Boot 项目的 pom.xml 文件中添加 Spring Security 和 MyBatis-Plus 的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>latest version</version> </dependency> ``` 2. 接下来,在项目的配置文件 application.properties 或 application.yml 中配置数据库连接和 MyBatis-Plus 的相关配置。 3. 创建一个用户实体类和对应的 Mapper 接口,使用 MyBatis-Plus 提供的注解和方法完成数据访问操作。 4. 创建一个自定义的 UserDetailsService 实现类,用于从数据库中获取用户信息,实现 loadUserByUsername 方法。 5. 创建一个自定义的 PasswordEncoder 实现类,用于加密和校验用户密码。 6. 配置 Spring Security,创建一个继承自 WebSecurityConfigurerAdapter 的类,并重写 configure 方法,设置用户认证规则、登录配置和访问控制规则。 7. 在 Spring Boot 启动类上使用 @MapperScan 注解,扫描 Mapper 接口。 通过以上步骤,就可以实现 Spring Security 与 MyBatis-Plus 的整合。在实际应用中,还可以根据具体需求进行一些其他配置和扩展,例如添加角色权限控制、自定义登录页面和处理逻辑等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大扑棱蛾子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值