spring security4 与 spring security3还是有一些区别的,目前这方面的资料很少,只能自己摸索,总结一些经验,记录下来
spring security4 取消了很多的setter注入方式,换成了构造器注入,其实在security3里有很多已经被@Deprecated,在security4里索性直接给删掉了
http节点中user-expressions属性security3默认是false,security4默认是true,
access-denied-page这个属性在security4中被删掉了,所以配置可以写成这样
<security:http use-expressions="false">
。。。。
<security:access-denied-handler error-page="/error"/>
。。。。
</security:http>
auto-config="true"配置这个属性会实现一个简单的验证,但是官方并不推荐这样做,配置如下
<security:http auto-config="true" use-expressions="false">
<security:intercept-url pattern="/login.html" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/resources/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/**" access="ROLE_USER" />
<security:access-denied-handler error-page="/error"/>
<security:logout logout-success-url="/" />
<security:form-login login-page="/login.html" default-target-url="/" authentication-failure-url="/login.html?error=1" always-use-default-target="true" />
</security:http>
再配置一个验证器
<security:authentication-manager>
<security:authentication-provider ref="authenticationProvider"/>
</security:authentication-manager>
<bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="hideUserNotFoundExceptions" value="false" />
<property name="userDetailsService" ref="userDetailsServiceImpl" />
<property name="passwordEncoder" ref="passwordEncoder" />
<property name="saltSource" ref="saltSource" />
</bean>
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
<bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
<property name="userPropertyToUse" value="username"/>
</bean>
这里用的是MD5加盐值的验证方式,内部的加密格式是: MD5(password{usernam}),如果不想用默认的加密格式可以覆写Md5PasswordEncoder这个类的这个mergePasswordAndSalt方法
public class Md5PasswordEncoder extends org.springframework.security.authentication.encoding.Md5PasswordEncoder {
protected String mergePasswordAndSalt(String password, Object salt, boolean strict) {
if(password == null) {
password = "";
}
if(strict && salt != null && (salt.toString().lastIndexOf("{") != -1 || salt.toString().lastIndexOf("}") != -1)) {
throw new IllegalArgumentException("Cannot use { or } in salt.toString()");
} else {
return salt != null && !"".equals(salt) ? MD5.getMD5ofStr(password).toUpperCase() + salt.toString() :password;
}
}
}