Spring-Security主要是一个由一堆Filter组成的过滤器链,每个Filter做自己的事情。今天我跟一下登录的密码认证过程,主要是UsernamePasswordAuthenticationFilter这个类
1.web.xml中配置security
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2. spring-security.xml 这里定义了一个ValidateCodeAuthenticationFilter,这个filter继承自 UsernamePasswordAuthenticationFilter,在做认证的时候调用UsernamePasswordAuthenticationFilter中的attemptAuthentication方法
<beans:bean id="validateCodeAuthenticationFilter" class="com.*.interceptors.ValidateCodeAuthenticationFilter">
<beans:property name="authenticationSuccessHandler" ref="customAuthenticationSuccessHandler"></beans:property>
<beans:property name="authenticationFailureHandler" ref="customAuthenticationFailureHandler"></beans:property>
<beans:property name="authenticationManager" ref="authenticationManager"></beans:property>
<beans:property name="filterProcessesUrl" value="/logincheck"></beans:property>
<beans:property name="usernameParameter" value="username"></beans:property>
<beans:property name="passwordParameter" value="password"></beans:property>
<beans:property name="allowEmptyValidateCode" value="${webLogin.allowEmptyValidateCode}" />
</beans:bean>
UsernamePasswordAuthenticationFilter中的attemptAuthentication方法将信息赋值给UsernamePasswordAuthenticationToken(authRequest),然后调用getAuthenticationManager().authenticate(authRequest)对用户密码的正确性进行验证,认证失败就抛出异常,成功就返回Authentication对象。
AuthenticationManager接口的实现类ProviderManager:
AuthenticationProvider接口的实现类AbstractUserDetailsAuthenticationProvider
改抽象方法的实现在 DaoAuthenticationProvider类
此处调用的loadUserByUsername即到达自定义实现的UserDetailService的loadUserByUsername,实现根据登录名查询数据库,返回UserDetails;