RBAC:基於角色的訪問控制(Role-Based Access Control)
先在web.xml 中配置一個過濾器(必須在Struts的過濾器以前)css
- <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>
而後就是編寫Spring安全的配置文件applicationContext-security.xml並配置到Spring解析的路徑下html
Spring Security主要作兩件事,一件是認證,一件是受權。java
認證
web
當用戶訪問受保護的信息卻沒有登陸得到認證時,框架會自動將請求跳轉到登陸頁面
在http標籤中的spring
- <form-login login-page="/page/login.jsp" />
配置。且該登陸頁面必須是不被攔截的。故要配置上數據庫
- <intercept-url pattern="/page/login.jsp" filters="none" />
Web項目的認證若是在HTTP標籤中配置了auto-config="true",框架就會自動的配置多8?個攔截器。 默認表單登陸認證的是FORM_LOGIN_FILTER攔截器,咱們能夠直接寫自定義的UserDetailsService,在這個類中實現方法 UserDetails loadUserByUsername(String username),從數據庫獲取用戶信息,以及其擁有的角色。緩存
- @Service("myUserDetailsService")
- public class MyUserDetailsServiceImpl extends BaseService implements UserDetailsService {
- @Resource
- private UserDao userDao;
-
-
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException, DataAccessException {
-
- User user = userDao.getUserByUsername(username);
- List<Role> roles = user.getRoles();
- Collection<GrantedAuthority> authorities = new LinkedList<GrantedAuthority>();
-
- for (Role role : roles) {
- authorities.add(new GrantedAuthorityImpl(role.getCode()));
- }
-
- UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),Constants.STATE_VALID.equals(user.getState()),true,true,true,authorities);
-
- return userDetails;
- }
-
-
- }
配置在安全
- <authentication-manager alias="myAuthenticationManager">
- <authentication-provider user-service-ref="myUserDetailsService">
- <password-encoder hash="md5" />
- </authentication-provider>
- </authentication-manager>
若是須要在登陸的時候,在HTTP SESSION中配置作些操做的。就得配置自定義的FORM_LOGIN_FILTER了 在HTTP標籤中加入session
- <custom-filter ref="loginFilter" before="FORM_LOGIN_FILTER" />
並配置app
- <beans:bean id="securityFilter"
- class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
- <beans:property name="authenticationManager" ref="myAuthenticationManager" />
- <beans:property name="accessDecisionManager"
- ref="affirmativeBasedAccessDecisionManager" />
- <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource"/>
- </beans:bean>
MyUsernamePasswordAuthenticationFilter 類是這麼寫的
- public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
- public static final String USERNAME = "username";
- public static final String PASSWORD = "password";
-
- @Resource
- private LoginService loginService;
- private UserLoginFormBean userLoginFormBean = new UserLoginFormBean();
-
- @Resource
- private LogService logService;
-
-
-
- @Override
- public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
- String username = obtainUsername(request);
- String password = obtainPassword(request);
-
- HttpSession session = request.getSession();
-
- userLoginFormBean.setUsername(obtainUsername(request));
- userLoginFormBean.setPassword(obtainPassword(request));
-
- User user = loginService.login(userLoginFormBean);
- session.setAttribute(Constants.SESSION_USER, user);
-
-
- Log log = new Log(user,getIpAddr(request),"用戶登陸", null);
- logService.add(log);
-
- UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
-
- setDetails(request, authRequest);
-
-
- return this.getAuthenticationManager().authenticate(authRequest);
- }
-
-
-
- }
getAuthenticationManager().authenticate(authRequest)是爲了讓UserDetailService提供Detailed的信息並認證
受權
在受權時,系統默認經過FILTER_SECURITY_INTERCEPTOR認證。
如需自定義受權攔截器,咱們在HTTP中在默認受權攔截器前配置了自定義的攔截器
- <custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR" />
本平臺採用基於請求URL地址的驗證方式
securityFilter的配置以下
- <beans:bean id="securityFilter"
- class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
- <beans:property name="authenticationManager" ref="myAuthenticationManager" />
- <beans:property name="accessDecisionManager"
- ref="affirmativeBasedAccessDecisionManager" />
- <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource"/>
- </beans:bean>
採用默認的自定義的也是採用Spring默認的FilterSecurityInterceptor攔截器,accessDecisionManager也採用的是框架提供的affirmativeBasedAccessDecisionManager
採用投票者來判斷是否受權。
- <beans:bean id="affirmativeBasedAccessDecisionManager"
- class="org.springframework.security.access.vote.AffirmativeBased">
- <beans:property name="decisionVoters" ref="roleDecisionVoter" />
- </beans:bean>
-
- <beans:bean name="roleDecisionVoter"
- class="org.springframework.security.access.vote.RoleVoter" />
-
- <beans:bean id="mySecurityMetadataSource"
- class="org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource">
- <beans:constructor-arg
- type="org.springframework.security.web.util.UrlMatcher" ref="antUrlPathMatcher" />
- <beans:constructor-arg type="java.util.LinkedHashMap"
- ref="securityRequestMapFactoryBean" />
- </beans:bean>
SecurityMetadataSource也是ss web框架提供的DefaultFilterInvocationSecurityMetadataSource,只是初始化參數中,一個選擇 antUrl匹配,仍是正則匹配,另外一個是提供自定義的經過securityRequestMapFactoryBean。在後者是一個 LinkedHashMap<RequestKey, Collection<ConfigAttribute>>類型,就是每個URL匹配模式,所須要角色的集合。
- @Service("securityRequestMapFactoryBean")
- public class SecurityRequestMapFactoryBean extends
- LinkedHashMap<RequestKey, Collection<ConfigAttribute>> {
-
- @Resource
- private ModuleDao moduleDao;
-
- @PostConstruct
- public void loadSecurityInfos(){
- List<Module> modules = moduleDao.getAll(new Module());
- for (Module module : modules) {
- RequestKey requestKey = new RequestKey(module.getPageUrl());
- Collection<ConfigAttribute> configAttributes = new LinkedList<ConfigAttribute>();
- for (final Role role : module.getRoles()) {
- configAttributes.add(new ConfigAttribute() {
- public String getAttribute() {
- return role.getCode();
- }
- });
- }
- this.put(requestKey, configAttributes);
- }
- }
-
- }
PS: 最終的件applicationContext-security.xml配置文件