Spring security 春季安全认证

Spring security 春季安全认证,spring-security,Spring Security,我正在开发一个基于Spring的应用程序,我正在使用SpringSecurity3.1.3。 每次我尝试进行身份验证时,身份验证都不会成功。以下是我的security-config.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-ins

我正在开发一个基于Spring的应用程序,我正在使用SpringSecurity3.1.3。 每次我尝试进行身份验证时,身份验证都不会成功。以下是我的security-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">

<security:http auto-config="true">
<security:form-login login-page="/app/main"
default-target-url="/app/account" />
<security:logout logout-url="/app/logout"
logout-success-url="/app/main" />
</security:http>

<bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt. BCryptPasswordEncoder" />

<security:authentication-manager alias="authenticationManager">
<security:authentication-provider
user-service-ref="userService" >
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>

<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication .dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userService" />
<property name="hideUserNotFoundExceptions" value="false" />
</bean>

<bean id="authenticationManager"
class="org.springframework.security.authentication .ProviderManager">
<constructor-arg>
<ref local="daoAuthenticationProvider" />
</constructor-arg>
</bean>


</beans>

我在数据库中存储用户名和编码密码。我可以在注册后第一次进行身份验证。原因是hibernate实体管理器在选择后会自动更新数据库中的密码值。我不知道为什么!!!当我使用纯文本密码时,这一切都不会发生,一切都正常。

很难确定,因为您没有详细说明什么是“我的bean”或在哪里使用此
setPassword
函数,但如果它是Hibernate实体的一部分,则可能会使用已编码的密码调用它(例如,从数据库加载实体时,而不仅仅是在创建新实体时)。此时您肯定不想使用bcrypt。这也可能解释了为什么您可以第一次登录,听起来很可能是您描述的hibernate自动更新字段

出于测试目的,请尝试添加一个断言来检查字符串是否以“$2a”开头(bcrypt字符串将以“$2a”开头),如果以“$2a”开头,则抛出异常


如果是这种情况,请确保在创建实体时在实体外部调用编码器,并将编码的密码传递给setter。

由于spring命名空间配置已将authenticationManager注册为提供程序管理器,因此不要显式为authenticationManagaer定义bean。Yuo只需添加
public void setPassword(String password) {
PasswordEncoder passwordEncoder= new BCryptPasswordEncoder();
this.password=passwordEncoder.encode(password);
}