最近用到了spring-security框架来实现登录验证。
以前做登录的步骤是:
1、用户输入用户名、密码登录
2、连接数据库对用户名、密码进行验证
3、获取用户信息(角色列表等等)
4、获取相关操作权限
security安全框架有点不同:
1、用户名、密码组合生成一个AuthenticationToken对象。
2、生成的这个token对象会传递给一个AuthenticationManager对象用于验证。
3、当成功认证后,AuthenticationManager返回一个Authentication对象。
4、接下来,就可以调用AuthenticationSuccessHandler成功处理器跳转首页或者登录之前访问的url。
先上spring-security.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<http pattern="/skin/**" security="none" />
<http pattern="/login.action" security="none" />
<http authentication-manager-ref="authenticationManager" entry-point-ref="customAuthenticationEntryPoint">
<!-- 初始化 -->
<intercept-url pattern="/init/**" access="hasRole('ROLE_ADMIN')" />
<!-- 登录 -->
<intercept-url pattern="/login.action*" access="permitAll" />
<!-- 用户管理(如果多个权限可以访问就用hasAnyRole('xx','cc')) -->
<intercept-url pattern="/user/*.action" access="hasRole('ROLE_ADMIN')" />
<!-- 其他 -->
<intercept-url pattern="/**" access="authenticated" />
<!-- 自定义认证过滤器 -->
<custom-filter ref="customAuthenticationFilter" position="FORM_LOGIN_FILTER" />
<!-- 自定义退出成功处理器 -->
<logout logout-url="/logout.action" success-handler-ref="customLogoutSuccessHandler" />
<headers>
<!-- Iframe页面允许被其它页面嵌入 -->
<frame-options disabled="true" />
</headers>
<csrf disabled="true" />
</http>
<!-- 认证管理器 -->
<authentication-manager alias="authenticationManager">
<authentication-provider ref="customAuthenticationProvider" />
</authentication-manager>
<!-- 认证服务提供者 -->
<beans:bean id="customAuthenticationProvider" class="com.identity.security.CustomAuthenticationProvider" />
<!-- 认证入口点 -->
<beans:bean id="customAuthenticationEntryPoint" class="com.identity.security.CustomAuthenticationEntryPoint">
<beans:constructor-arg name="pcLoginUrl" value="/login.action" />
</beans:bean>
<!-- 认证过滤器 -->
<beans:bean id="customAuthenticationFilter" class="com.identity.security.CustomAuthenticationFilter">
<beans:constructor-arg name="filterProcessesUrl" value</