spring security 3.0 兑现认证与授权
spring security 3.0 实现认证与授权先看一下spring security 官方对以下几个类或接口的解释,因为这个几个
spring security 3.0 实现认证与授权
先看一下spring security 官方对以下几个类或接口的解释,因为这个几个类在程序中会使用到;
ConfigAttribute:Stores a security system related configuration attribute.
SecurityConfig:ConfigAttribute的实现类。
GrantedAuthority:Represents an authority granted to an Authentication object.
GrantedAuthorityImpl:GrantedAuthority的实现类。
UserDetails:Provides core user information.
Authentication:Represents the token for an authentication request or for an authenticated principal once the request has been processed by the AuthenticationManager.authenticate(Authentication) method.
UserDetailsService:Core interface which loads user-specific data.
FilterInvocationSecurityMetadataSource:Marker interface for SecurityMetadataSource implementations that are designed to perform lookups keyed on FilterInvocations.
AccessDecisionManager:Makes a final access control (authorization) decision.
?
定义四张表:用户表、角色表、资源表、组织机构表(可选)
?
首先需要在web.xml文件中添加以下配置:
package?xxx.xxx.xxx.commons.permissionengine.web.security;????import?java.util.Collection;??import?java.util.Iterator;????import?org.springframework.security.access.AccessDecisionManager;??import?org.springframework.security.access.AccessDeniedException;??import?org.springframework.security.access.ConfigAttribute;??import?org.springframework.security.access.SecurityConfig;??import?org.springframework.security.authentication.InsufficientAuthenticationException;??import?org.springframework.security.core.Authentication;??import?org.springframework.security.core.GrantedAuthority;????/**??*?决策管理器,用于判断用户需要访问的资源与用户所拥有的角色是否匹配??*?@author?Keven??*??*/??public?class?SecurityAccessDecisionManager?implements?AccessDecisionManager?{????????@Override??????public?void?decide(Authentication?authentication,?Object?object,?Collection<ConfigAttribute>?configAttributes)?throws?AccessDeniedException,?InsufficientAuthenticationException?{??????????if(configAttributes?==?null)??????????????return;??????????//获取资源与角色对应关系列表??????????Iterator<ConfigAttribute>?iter?=?configAttributes.iterator();??????????while(iter.hasNext())?{??????????????ConfigAttribute?configAttribute?=?iter.next();??????????????//获取访问该资源需要的角色??????????????String?needRole?=?((SecurityConfig)configAttribute).getAttribute();??????????????//从上下文环境获取用户所具有的角色??????????????for(GrantedAuthority?grantedAuthority?:?authentication.getAuthorities())?{??????????????????//判断用户拥有的角色是否与访问该资源所需要的角色匹配??????????????????if(needRole.equals(grantedAuthority.getAuthority()))??????????????????????return;??????????????}??????????}??????????throw?new?AccessDeniedException("权限不足!");??????}????????@Override??????public?boolean?supports(ConfigAttribute?arg0)?{??????????return?true;??????}????????@Override??????public?boolean?supports(Class<?>?arg0)?{??????????return?true;??????}??}?