SpringSecurity【資源和許可權加入到資料庫】
阿新 • • 發佈:2019-01-03
Learn-SpringSecurity
學習SpringSecurity時,寫的小案例。
已達目標:完成了資源與許可權的資料庫持久化。
主要功能實現都是歸功於該部落格:學習部落格地址
你只需要寫一個類,就是下面的類,再把該類配置一下(配置在SpringSecurity.xml裡面)就能夠實現上面的目標了。 該打註釋的地方,我寫了的,祝福你能夠看懂,謝謝!!!
/**
* Created by Administrator on 2017/8/9.
*/
public class URLFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource,InitializingBean{
//許可權集合
private Map<String, Collection<ConfigAttribute>> requestMap;
/**
* 2、afterPropertiesSet方法,初始化bean的時候執行,
* 可以針對某個具體的bean進行配置。afterPropertiesSet 必須實現 InitializingBean介面。
* 實現 InitializingBean介面必須實現afterPropertiesSet方法。
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
requestMap = loadAllResource();
}
/**
* 該方法用作 RequestMap 的資料重新整理。
*/
public void refreshRequestData(){
try {
afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
}
}
@Autowired
private ResMapper resMapper;
@Autowired
private ResRoleMapper resRoleMapper;
/**
* 該方法目的是查詢資料庫裡面的 String(代表URL),和該 URL 所需要的許可權 Collection<ConfigAttribute>
* @return
*/
private Map<String,Collection<ConfigAttribute>> loadAllResource(){
//宣告一個快取容器,快取所有關於資源和許可權的資訊。
Map<String , Collection<ConfigAttribute>> result = new HashMap<>();
//初始化所有的資源對應的許可權資訊。
List<Res> res = resMapper.findAllRes();
for (Res resi : res) {
//遍歷URL
String url = resi.getRes_url();
//通過 URL 查詢出所有關於該資源的許可權資訊。
//這裡 我把 url 封裝了一下,把 url 放進了 Res 實體類裡面。
Res requestMessage = new Res("",url,"");
List<Role> roles = resRoleMapper.findAllRolesByRes(requestMessage);
//開始封裝當前資源對應的許可權資訊。
Collection<ConfigAttribute> attrs = new ArrayList<>();
for (Role role : roles) {
attrs.add(new SecurityConfig(role.getRname()));
}
result.put(url,attrs);
}
return result;
}
/**
* 每次使用者登入時,都會呼叫該方法。你可以檢視方法發裡面的輸出!!!
* @param object
* @return
* @throws IllegalArgumentException
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
String url = ((FilterInvocation)object).getRequestUrl();
System.out.println(url);
System.out.println(requestMap.get(url));
return requestMap.get(url);
}
/**
* getAllConfigAttributes方法如果返回了所有定義的許可權資源,
* Spring Security會在啟動時校驗每個ConfigAttribute是否配置正確,不需要校驗直接返回null。
* @return
*/
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
Collection<ConfigAttribute> allConfigAttrs = new ArrayList<>();
System.out.println("呼叫了 getAllConfigAttributes()方法!!!");
Set<String> set = requestMap.keySet();
for (String s : set) {
allConfigAttrs.addAll(requestMap.get(s));
}
return allConfigAttrs;
}
/**
* supports方法返回類物件是否支援校驗,
* web專案一般使用FilterInvocation來判斷,或者直接返回true。
* 在上面我們主要定義了兩個許可權碼:
* @param clazz
* @return
*/
@Override
public boolean supports(Class<?> clazz) {
return FilterInvocation.class.isAssignableFrom(clazz);
}
}
還有配置檔案:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置不過濾的資源(靜態資源及登入相關) -->
<security:http pattern="/**/*.css" security="none"></security:http>
<security:http pattern="/**/*.jpg" security="none"></security:http>
<security:http pattern="/**/*.jpeg" security="none"></security:http>
<security:http pattern="/**/*.gif" security="none"></security:http>
<security:http pattern="/**/*.png" security="none"></security:http>
<security:http pattern="/**/*.js" security="none"></security:http>
<security:http pattern="/login.jsp" security="none"></security:http>
<security:http pattern="/index.jsp" security="none"></security:http>
<security:http pattern="/getCode" security="none" /><!-- 不過濾驗證碼 -->
<security:http pattern="/test/**" security="none"></security:http><!-- 不過濾測試內容 -->
<!-- 配置資源許可權資訊 -->
<security:http auto-config="true" use-expressions="false">
<security:custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>
<!-- 配置登出 -->
<!-- 有時候,你會發現,就算重啟了 Tomcat ,session 也不會過期,那麼你需要配置退出時,session 過期。 -->
<security:logout logout-url="/logoutSecurity" invalidate-session="true" delete-cookies="JSESSIONID"/>
<!-- 在配置登出時,如果不把 csrf 設定為 true 的話,那麼登出時的連結將會發生 404 錯誤。 -->
<security:csrf disabled="true"/>
</security:http>
<!-- 配置使用者角色資訊 -->
<security:authentication-manager alias="authenticationManagerw">
<security:authentication-provider user-service-ref="customUserService">
</security:authentication-provider>
</security:authentication-manager>
<bean id="MyaccessManager" class="org.springframework.security.access.vote.AffirmativeBased">
<constructor-arg name="decisionVoters">
<list>
<ref bean="roleVoter"/>
<ref bean="authVoter"/>
</list>
</constructor-arg>
</bean>
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
<property name="rolePrefix" value="ROLE_"/>
</bean>
<bean id="authVoter" class="org.springframework.security.access.vote.AuthenticatedVoter"/>
<bean id="securityMetadataSource" class="cn.domarvel.springsecurity.model.URLFilterInvocationSecurityMetadataSource" />
<!-- 資料庫管理url -->
<bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="accessDecisionManager" ref="MyaccessManager"></property>
<property name="authenticationManager" ref="authenticationManagerw"></property>
<property name="securityMetadataSource" ref="securityMetadataSource"></property>
</bean>
</beans>