Spring--Security
在开发中经常会有需要在页面被访问时进行权限判断. 我们不可能在每个页面里进行各自的判断.显然应该将它做为一个切面来做.在WEB开发中可以使用过滤器.在过滤器里面集合进行判断.这样在判断逻辑变更时也能很快应对.在SSH的开发中可以手动写过滤器,也可以建Struts拦截器.还有一个功能较大的方案就是Spring的Security解决方案.
Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。
用户认证 一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。
用户授权 指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。
Spring验证方式有多种,可以将信息放在数据库中,然后在过滤器中定义数据库访问等信息,完成在数据库中取值进行比较.也可以自定义逻辑的比较.这里只说自定义逻辑的比较
下面是将Security 加到系统中的流程:
1.在 web.xml 中添加 Spring Security 的过滤器.在 web.xml 中加入如下代码:
<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>
public class CustomSecurityFilter extends AbstractPreAuthenticatedProcessingFilter {@Overridepublic void doFilterHttp(HttpServletRequest request, HttpServletResponse response,FilterChain filterChain) throws IOException, ServletException {if (logger.isDebugEnabled()) {logger.debug("检查权限: "+ SecurityContextHolder.getContext().getAuthentication());}SecurityContextHolder.getContext().setAuthentication(null);super.doFilterHttp(request, response, filterChain);}// 一个实现了UserDetails接口的对象(权限主体)private AuthenticationUserDetailsService authenticationUserDetailsService;@Overrideprotected Object getPreAuthenticatedCredentials(HttpServletRequest request) {// 从SESSION中取用户权限HttpSession nowSession = request.getSession(false);UserInfoDto userInfo = null;List<UserRightDto> rightList = new ArrayList<UserRightDto>();UserRightDto noAccess = new UserRightDto();noAccess.setId(SystemConst.ROLE_NOACCESS);if (null == nowSession) {return rightList;}userInfo = (UserInfoDto) nowSession.getAttribute(SystemConst.LOGIN_USER_INFO);if (null == userInfo) {return rightList;}if (userInfo.getRightList() == null || userInfo.getRightList().size() <= 0) {return rightList;}return userInfo.getRightList();}@Overrideprotected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {return authenticationUserDetailsService;}@Overridepublic int getOrder() {// AbstractPreAuthenticatedProcessingFilter类上进行扩展返回预验证过滤器位置return FilterChainOrder.PRE_AUTH_FILTER;}// -------------以下是getter setter方法-------------//public AuthenticationUserDetailsService getAuthenticationUserDetailsService() {return authenticationUserDetailsService;}public void setAuthenticationUserDetailsService(AuthenticationUserDetailsService authenticationUserDetailsService) {this.authenticationUserDetailsService = authenticationUserDetailsService;}}
CustomSecurityuserInfoService.javapackage cn.panasonic.common.interceptor.security;import java.util.HashMap;import java.util.List;import java.util.Map;import org.springframework.security.Authentication;import org.springframework.security.GrantedAuthority;import org.springframework.security.GrantedAuthorityImpl;import org.springframework.security.userdetails.AuthenticationUserDetailsService;import org.springframework.security.userdetails.UserDetails;import org.springframework.security.userdetails.UsernameNotFoundException;import cn.panasonic.common.dto.UserRightDto;import cn.panasonic.common.utility.SystemConst;public class CustomSecurityuserInfoService implements AuthenticationUserDetailsService {// 用户集保存Mapprivate Map<String, BaseUserDetails> userMap = null;@SuppressWarnings("unchecked")@Overridepublic UserDetails loadUserDetails(Authentication token)throws UsernameNotFoundException {// 当前访问者的权限列表List<UserRightDto> rightList = (List<UserRightDto>) token.getCredentials();if (rightList == null || rightList.size() <= 0) {return new BaseUserDetails(SystemConst.ROLE_NOACCESS,SystemConst.ROLE_NOACCESS,new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_NOACCESS") });}GrantedAuthority[] rightArr = new GrantedAuthority[rightList.size()];// 根据当前访问者的权限列表返回它在Spring中的权限.for (int i = 0; i < rightList.size(); i++) {rightArr[i] = userMap.get(rightList.get(i).getId()).getAuthorities()[0];}BaseUserDetails user = new BaseUserDetails("username", "password", rightArr);return user;}public CustomSecurityuserInfoService() {userMap = new HashMap<String, BaseUserDetails>();// 都无法访问BaseUserDetails userInfo = null;userInfo = new BaseUserDetails(SystemConst.ROLE_NOACCESS,SystemConst.ROLE_NOACCESS,new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_NOACCESS") });userMap.put(SystemConst.ROLE_NOACCESS, userInfo);// 管理员权限userInfo = null;userInfo = new BaseUserDetails(SystemConst.ROLE_ADMIN, SystemConst.ROLE_ADMIN,new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_ADMIN") });userMap.put(SystemConst.ROLE_ADMIN, userInfo);}}
配置已经完成.将项目发布到WEB容器中.启动容器时,CustomSecurityuserInfoService.java 会先被初始化,所以它的构造函数会被执行,就是上面的初始化所有权限.
在我们访问项目的页面时,如上面已经配置的:user0101Actin.do.这时候CustomSecurityFilter.java的doFilterHttp被执行.过滤开始.然后就是getPreAuthenticatedCredentials方法.这时候用户所有的认证信息会被返回.最后执行的就是CustomSecurityuserInfoService.java的loadUserDetails方法.这就是关键.上面步骤返回的是它在系统中的权限.而这里要返回的是该用户在Spring Security上下文中的认证信息.记得上面配置URL时在后面的access后会有ROLE_ADMIN,ROLE_NROMAL这样的配置.Spring Security会在这里返回的用户认证信息的权限列表中查看,是否包含access列表中的某一个,如果包含任意一个,就表示是有访问权限.
简单来说,要想访问通过,就要在loadUserDetails返回的用户信息的权限列表:GrantedAuthority[]中包括URL后设置可访问权限字符串中的一个.
原文地址:http://blog.sina.com.cn/s/blog_5f54f0be0100u7wd.html