一、数据库结构
先来看一下数据库结构,采用的是基于角色-资源-用户的权限管理设计。(MySql数据库)
1.用户表Users
create table `users` (
-- 账号是否有限 1. 是 0.否
`enable` int(11) default null,
`password` varchar(255) default null,
`account` varchar(255) default null,
`id` int(11) not null auto_increment,
primary key (`id`)
)
2.角色表Roles
CREATE TABLE `roles` (
`enable` int(11) default NULL,
`name` varchar(255) default NULL,
`id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`id`)
)
3 用户_角色表users_roles
CREATE TABLE `users_roles` (
--用户表的外键
`uid` int(11) default NULL,
--角色表的外键
`rid` int(11) default NULL,
`urId` int(11) NOT NULL auto_increment,
PRIMARY KEY (`urId`),
KEY `rid` (`rid`),
KEY `uid` (`uid`),
CONSTRAINT `users_roles_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `roles` (`id`),
CONSTRAINT `users_roles_ibfk_2` FOREIGN KEY (`uid`) REFERENCES `users` (`id`)
)
4.资源表resources
CREATE TABLE `resources` (
`memo` varchar(255) default NULL,
-- 权限所对应的url地址
`url` varchar(255) default NULL,
--优先权
`priority` int(11) default NULL,
--类型
`type` int(11) default NULL,
--权限所对应的编码,例201代表发表文章
`name` varchar(255) default NULL,
`id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`id`)
)
5.角色_资源表roles_resources
CREATE TABLE `roles_resources` (
`rsid` int(11) default NULL,
`rid` int(11) default NULL,
`rrId` int(11) NOT NULL auto_increment,
PRIMARY KEY (`rrId`),
KEY `rid` (`rid`),
KEY `roles_resources_ibfk_2` (`rsid`),
CONSTRAINT `roles_resources_ibfk_2` FOREIGN KEY (`rsid`) REFERENCES `resources` (`id`),
CONSTRAINT `roles_resources_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `roles` (`id`)
)
二、系统配置
1) web.xml
<!-- Spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml,classpath:applicationContext-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 权限 -->
<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>
这里主要是配置了让容器启动的时候加载application-security.xml和Spring Security的权限过滤器代理,让其过滤所有的客服请求。
2)application-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<global-method-security pre-post-annotations="enabled" />
<!-- 该路径下的资源不用过滤 -->
<http pattern="/js/**" security="none"/>
<http use-expressions="true" auto-config="true">
<form-login />
<logout/>
<!-- 实现免登陆验证 -->
<remember-me />
<session-management invalid-session-url="/timeout.jsp">
<concurrency-control max-sessions="10" error-if-maximum-exceeded="true" />
</session-management>
<custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
</http>
<!-- 配置过滤器 -->
<beans:bean id="myFilter" class="com.huaxin.security.MySecurityFilter">
<!-- 用户拥有的权限 -->
<beans:property name="authenticationManager" ref="myAuthenticationManager" />
<!-- 用户是否拥有所请求资源的权限 -->
<beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
<!-- 资源与权限对应关系 -->
<beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
</beans:bean>
<!-- 实现了UserDetailsService的Bean -->
<authentication-manager alias="myAuthenticationManager">
<authentication-provider user-service-ref="myUserDetailServiceImpl" />
</authentication-manager>
<beans:bean id="myAccessDecisionManager" class="com.huaxin.security.MyAccessDecisionManager"></beans:bean>
<beans:bean id="mySecurityMetadataSource" class="com.huaxin.security.MySecurityMetadataSource">
<beans:constructor-arg name="resourcesDao" ref="resourcesDao"></beans:constructor-arg>
</beans:bean>
<beans:bean id="myUserDetailServiceImpl" class="com.huaxin.security.MyUserDetailServiceImpl">
<beans:property name="usersDao" ref="usersDao"></beans:property>
</beans:bean>
</beans:beans>
我们在第二个http标签下配置一个我们自定义的继承了org.springframework.security.access.intercept.AbstractSecurityInterceptor的Filter,并注入其
必须的3个组件authenticationManager、accessDecisionManager和securityMetadataSource。其作用上面已经注释了。
<custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/> 这里的FILTER_SECURITY_INTERCEPTOR是Spring Security默认的Filter,
我们自定义的Filter必须在它之前,过滤客服请求。接下来看下我们最主要的myFilter吧。
3)myFilter
(1) MySecurityFilter.java 过滤用户请求
public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {
//与applicationContext-security.xml里的myFilter的属性securityMetadataSource对应,
//其他的两个组件,已经在AbstractSecurityInterceptor定义
private FilterInvocationSecurityMetadataSource securityMetadataSource;
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
private void invoke(FilterInvocation fi) throws IOException, ServletException {
// object为FilterInvocation对象
//super.beforeInvocation(fi);源码
//1.获取请求资源的权限
//执行Collection<ConfigAttribute> attributes = SecurityMetadataSource.getAttributes(object);
//2.是否拥有权限
//this.accessDecisionManager.decide(authenticated, object, attributes);
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
}
public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
return securityMetadataSource;
}
public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public Class<? extends Object> getSecureObjectClass() {
//下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
return FilterInvocation.class;
}
}
核心的InterceptorStatusToken token = super.beforeInvocation(fi);会调用我们定义的accessDecisionManager:decide(Object object)和securityMetadataSource
:getAttributes(Object object)方法。
(2)MySecurityMetadataSource.java
//1 加载资源与权限的对应关系
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
//由spring调用
public MySecurityMetadataSource(ResourcesDao resourcesDao) {
this.resourcesDao = resourcesDao;
loadResourceDefine();
}
private ResourcesDao resourcesDao;
private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
public ResourcesDao getResourcesDao() {
return resourcesDao;
}
public void setResourcesDao(ResourcesDao resourcesDao) {
this.resourcesDao = resourcesDao;
}
public Collection<ConfigAttribute> getAllConfigAttributes() {
// TODO Auto-generated method stub
return null;
}
public boolean supports(Class<?> clazz) {
// TODO Auto-generated method stub
return true;
}
//加载所有资源与权限的关系
private void loadResourceDefine() {
if(resourceMap == null) {
resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
List<Resources> resources = this.resourcesDao.findAll();
for (Resources resource : resources) {
Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
//以权限名封装为Spring的security Object
ConfigAttribute configAttribute = new SecurityConfig(resource.getName());
configAttributes.add(configAttribute);
resourceMap.put(resource.getUrl(), configAttributes);
}
}
Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet();
Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator();
}
//返回所请求资源所需要的权限
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
String requestUrl = ((FilterInvocation) object).getRequestUrl();
System.out.println("requestUrl is " + requestUrl);
if(resourceMap == null) {
loadResourceDefine();
}
return resourceMap.get(requestUrl);
}
}
这里的resourcesDao,熟悉Dao设计模式和Spring 注入的朋友应该看得明白。
(3)MyUserDetailServiceImpl.java
public class MyUserDetailServiceImpl implements UserDetailsService {
private UsersDao usersDao;
public UsersDao getUsersDao() {
return usersDao;
}
public void setUsersDao(UsersDao usersDao) {
this.usersDao = usersDao;
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("username is " + username);
Users users = this.usersDao.findByName(username);
if(users == null) {
throw new UsernameNotFoundException(username);
}
Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);
boolean enables = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
User userdetail = new User(users.getAccount(), users.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
return userdetail;
}
//取得用户的权限
private Set<GrantedAuthority> obtionGrantedAuthorities(Users user) {
Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
Set<Roles> roles = user.getRoles();
for(Roles role : roles) {
Set<Resources> tempRes = role.getResources();
for(Resources res : tempRes) {
authSet.add(new GrantedAuthorityImpl(res.getName()));
s }
}
return authSet;
}
}
(4) MyAccessDecisionManager.java
public class MyAccessDecisionManager implements AccessDecisionManager {
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if(configAttributes == null) {
return;
}
//所请求的资源拥有的权限(一个资源对多个权限)
Iterator<ConfigAttribute> iterator = configAttributes.iterator();
while(iterator.hasNext()) {
ConfigAttribute configAttribute = iterator.next();
//访问所请求资源所需要的权限
String needPermission = configAttribute.getAttribute();
System.out.println("needPermission is " + needPermission);
//用户所拥有的权限authentication
for(GrantedAuthority ga : authentication.getAuthorities()) {
if(needPermission.equals(ga.getAuthority())) {
return;
}
}
}
//没有权限
throw new AccessDeniedException(" 没有权限访问! ");
}
public boolean supports(ConfigAttribute attribute) {
// TODO Auto-generated method stub
return true;
}
public boolean supports(Class<?> clazz) {
// TODO Auto-generated method stub
return true;
}
}
三、流程
1)容器启动(MySecurityMetadataSource:loadResourceDefine加载系统资源与权限列表)
2)用户发出请求
3)过滤器拦截(MySecurityFilter:doFilter)
4)取得请求资源所需权限(MySecurityMetadataSource:getAttributes)
5)匹配用户拥有权限和请求权限(MyAccessDecisionManager:decide),如果用户没有相应的权限,
执行第6步,否则执行第7步。
6)登录
7)验证并授权(MyUserDetailServiceImpl:loadUserByUsername)
8)重复4,5
提到的MyUserDetailServiceImpl获取用户权限,在用户没有登陆的时候,Spring Security会让我们自动跳转到默认的登陆界面,但在实际应用绝大多数是用我们自己的登陆界面的,其中就包括一些我们自己的逻辑,比如验证码。因此下面就说下怎么自定义登录验证
二、Spring Security的过滤器
通过DEBUG可以看到Spring Security的Filter的顺序
Security filter chain: [
ConcurrentSessionFilter
SecurityContextPersistenceFilter
LogoutFilter
MyUsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
RememberMeAuthenticationFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
MySecurityFilter
FilterSecurityInterceptor
]
Spring Security的登陆验证用的就是MyUsernamePasswordAuthenticationFilter,所以要实现我们自己的验证,可以写一个类并继承MyUsernamePasswordAuthenticationFilter类,重写attemptAuthentication方法。
三、applicationContext-Security.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<debug/>
<http pattern="/js/**" security="none"/>
<http pattern="/resource/**" security="none"></http>
<http pattern="/login.jsp" security="none"/>
<http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint">
<logout/>
<!-- 实现免登陆验证 -->
<remember-me />
<session-management invalid-session-url="/timeout.jsp">
<concurrency-control max-sessions="10" error-if-maximum-exceeded="true" />
</session-management>
<custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER" />
<custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
</http>
<!-- 登录验证器 -->
<beans:bean id="loginFilter"
class="com.huaxin.security.MyUsernamePasswordAuthenticationFilter">
<!-- 处理登录的action -->
<beans:property name="filterProcessesUrl" value="/j_spring_security_check"></beans:property>
<!-- 验证成功后的处理-->
<beans:property name="authenticationSuccessHandler" ref="loginLogAuthenticationSuccessHandler"></beans:property>
<!-- 验证失败后的处理-->
<beans:property name="authenticationFailureHandler" ref="simpleUrlAuthenticationFailureHandler"></beans:property>
<beans:property name="authenticationManager" ref="myAuthenticationManager"></beans:property>
<!-- 注入DAO为了查询相应的用户 -->
<beans:property name="usersDao" ref="usersDao"></beans:property>
</beans:bean>
<beans:bean id="loginLogAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/index.jsp"></beans:property>
</beans:bean>
<beans:bean id="simpleUrlAuthenticationFailureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<!-- 可以配置相应的跳转方式。属性forwardToDestination为true采用forward false为sendRedirect -->
<beans:property name="defaultFailureUrl" value="/login.jsp"></beans:property>
</beans:bean>
<!-- 认证过滤器 -->
<beans:bean id="securityFilter" class="com.huaxin.security.MySecurityFilter">
<!-- 用户拥有的权限 -->
<beans:property name="authenticationManager" ref="myAuthenticationManager" />
<!-- 用户是否拥有所请求资源的权限 -->
<beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
<!-- 资源与权限对应关系 -->
<beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
</beans:bean>
<!-- 实现了UserDetailsService的Bean -->
<authentication-manager alias="myAuthenticationManager">
<authentication-provider user-service-ref="myUserDetailServiceImpl" />
</authentication-manager>
<beans:bean id="myAccessDecisionManager" class="com.huaxin.security.MyAccessDecisionManager"></beans:bean>
<beans:bean id="mySecurityMetadataSource" class="com.huaxin.security.MySecurityMetadataSource">
<beans:constructor-arg name="resourcesDao" ref="resourcesDao"></beans:constructor-arg>
</beans:bean>
<beans:bean id="myUserDetailServiceImpl" class="com.huaxin.security.MyUserDetailServiceImpl">
<beans:property name="usersDao" ref="usersDao"></beans:property>
</beans:bean>
<!-- 未登录的切入点 -->
<beans:bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/login.jsp"></beans:property>
</beans:bean>
</beans:beans>
这里特别要说明一下,我们的<http>标签不能配置auto-config,因为这样配置后,依然会采用Spring Security的Filter Chain会与下面我们配的custom-filter冲突,最好会抛异常。还有配置一个切入点entry-point-ref="authenticationProcessingFilterEntryPoint",为了在未登陆的时候,跳转到哪个页面,不配也会抛异常。
<custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER" /> position表示替换掉Spring Security原来默认的登陆验证Filter。
四、MyUsernamePasswordAuthenticationFilter
package com.huaxin.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.huaxin.bean.Users;
import com.huaxin.dao.UsersDao;
/*
*
* UsernamePasswordAuthenticationFilter源码
attemptAuthentication
this.getAuthenticationManager()
ProviderManager.java
authenticate(UsernamePasswordAuthenticationToken authRequest)
AbstractUserDetailsAuthenticationProvider.java
authenticate(Authentication authentication)
P155 user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
DaoAuthenticationProvider.java
P86 loadUserByUsername
*/
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
public static final String VALIDATE_CODE = "validateCode";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
private UsersDao usersDao;
public UsersDao getUsersDao() {
return usersDao;
}
public void setUsersDao(UsersDao usersDao) {
this.usersDao = usersDao;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
//检测验证码
checkValidateCode(request);
String username = obtainUsername(request);
String password = obtainPassword(request);
//验证用户账号与密码是否对应
username = username.trim();
Users users = this.usersDao.findByName(username);
if(users == null || !users.getPassword().equals(password)) {
/*
在我们配置的simpleUrlAuthenticationFailureHandler处理登录失败的处理类在这么一段
这样我们可以在登录失败后,向用户提供相应的信息。
if (forwardToDestination) {
request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
} else {
HttpSession session = request.getSession(false);
if (session != null || allowSessionCreation) {
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
}
}
*/
throw new AuthenticationServiceException("用户名或者密码错误!");
}
//UsernamePasswordAuthenticationToken实现 Authentication
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// Place the last username attempted into HttpSession for views
// 允许子类设置详细属性
setDetails(request, authRequest);
// 运行UserDetailsService的loadUserByUsername 再次封装Authentication
return this.getAuthenticationManager().authenticate(authRequest);
}
protected void checkValidateCode(HttpServletRequest request) {
HttpSession session = request.getSession();
String sessionValidateCode = obtainSessionValidateCode(session);
//让上一次的验证码失效
session.setAttribute(VALIDATE_CODE, null);
String validateCodeParameter = obtainValidateCodeParameter(request);
if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {
throw new AuthenticationServiceException("验证码错误!");
}
}
private String obtainValidateCodeParameter(HttpServletRequest request) {
Object obj = request.getParameter(VALIDATE_CODE);
return null == obj ? "" : obj.toString();
}
protected String obtainSessionValidateCode(HttpSession session) {
Object obj = session.getAttribute(VALIDATE_CODE);
return null == obj ? "" : obj.toString();
}
@Override
protected String obtainUsername(HttpServletRequest request) {
Object obj = request.getParameter(USERNAME);
return null == obj ? "" : obj.toString();
}
@Override
protected String obtainPassword(HttpServletRequest request) {
Object obj = request.getParameter(PASSWORD);
return null == obj ? "" : obj.toString();
}
}
有时间,大家看看源码吧。
五、login.jsp
<body>
<span style="color:red"><%=session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) %></span>
<form action="j_spring_security_check" method="post">
Account:<Input name="username"/><br/>
Password:<input name="password" type="password"/><br/>
<input value="submit" type="submit"/>
</form>
</body>