山哥做的網(wǎng)站本來已經(jīng)有登陸控制,用JDBC來存SessionId相關(guān)的信息。但是權(quán)限控制的設(shè)計(jì)在擴(kuò)展性方面不太好。于是想試試高大上的 Spring Security ,聽說Apache Shino也不錯(cuò)而且簡單很多,但是Spring 的Actuator要用Spring Security,只好硬著頭皮啃這件難啃的貨了。用過之后,發(fā)現(xiàn)這貨真的像網(wǎng)上人民吐槽的那樣,相當(dāng)?shù)膹?fù)雜麻煩!有好幾次想放棄不用它了,但是憑著不服輸?shù)木瘢€是鉆研了下去。花了一個(gè)星期的工余時(shí)間,總算把原來的解決方案遷移到了Spring Security上。過程之中填坑無數(shù),結(jié)果卻是喜人的!于是紀(jì)錄一下一些重要的point。
至于Spring Cache,上了Spring Security 之后,如果不上Cache,那性能我相信是慘不忍暏的!為什么?但凡登陸驗(yàn)證,你得和數(shù)據(jù)庫里的username和password來compare吧?它的jdbc模式雖然自帶Cache,但我不想填更多的坑,于是自己實(shí)現(xiàn)一個(gè) UserDetailsService, 這樣我的數(shù)據(jù)庫結(jié)構(gòu)自由很多,甚至以后不用關(guān)系型 數(shù)據(jù)庫也可以。用了debug模式,發(fā)現(xiàn)訪問每個(gè)頁面它都會(huì)調(diào)用一次UserDetailsService,我不想測(cè)試它每次去讀數(shù)據(jù)庫的性能,人生苦短啊大叔!上緩存吧!!
Issue 1, 這個(gè)問題是 Spring Cache 貢獻(xiàn)出來的。如果你也用同樣的寫法,可能你在開發(fā)環(huán)境沒問題,但生產(chǎn)環(huán)境一定會(huì)遇到。
出錯(cuò)信息:java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?)
根本原因:以下代碼里,自定義了Key,于是Key generator不起效,它會(huì)用SpEL來把 name 這個(gè)參數(shù)作為Key。這是官網(wǎng)教程的例子,為什么會(huì)行不通呢?再反復(fù)斟酌官網(wǎng)教程,終于明白它說什么了,就是如果編譯沒選debug模式,編譯出來的class文件是沒有參數(shù)名的信息的,那么反射機(jī)制來獲取這個(gè)參數(shù)的值,就找不到參數(shù)名字!只能用 #a0或者#p0來指代第一個(gè)參數(shù),依此類推。(If for some reason the names are not available (e.g. no debug information), the argument names are also available under the #a<#arg> where #arg stands for the argument index (starting from 0).)
會(huì)出錯(cuò)的寫法,引用 參數(shù) name作為Cache的key。
@Cacheable(cachnames="user", key="#name")
public User findByName(String name);
正確的萬能寫法,這里把 user_ 作為 key的前綴,傳參 name作為后綴。大功告成!親個(gè)嘴兒!
@Cacheable(cachnames="user", key="'user_'.concat(#a0)")
public User findByName(String name);
Issue 2,如果你的Entity類作為Cache, 用了JCache,那么一定要實(shí)現(xiàn)Serializable,里面所有的集合類,所有的自定義類,都要是Serializable。(比如ArrayList, LinkedList, ConcurrentSet等等都可以)
如果你做了Join Table,那么不能用LAZY的方式Join,否則從緩存解出來就會(huì)有問題。一定要用EAGER。
Join Table一定要注意,你的類返回不可以是Null紀(jì)錄,否則從緩存解出來無法還原成一個(gè)真實(shí)的Entity,又會(huì)出錯(cuò)…
Issue 3, 用了Spring Security之后,頁面ajax里的POST方法失效!Chrome環(huán)境下看,返回代碼是 403 Forbidden。
出錯(cuò)原因: csrf 是默認(rèn)啟用的,如果是thymeleaf作為渲染器,在html form里面,spring security會(huì)自動(dòng)加入一個(gè)hidden的 _csrf.token,可是 如果你上了 ajax,那臣妾就表示無能為力了。。
解決方案:請(qǐng)看如下兩步驟,用來解決jquery的ajax request for POST:
Step 1, 在<head>里加如下function
<script type="text/javascript">
function sendCsrfHeader (request) {
var token = '[[${_csrf.token}]]';
var header = '[[${_csrf.headerName}]]';
request.setRequestHeader(header, token);
}
</script>
Step 2, 在每個(gè) POST的ajax里面,加上beforeSend:
$.ajax({
type : "POST",
url : [[@{/user/changePassword}]],
dataType : 'json',
async : true,
data : { },
beforeSend: function(request) {
sendCsrfHeader(request);
},
success : function(responseText) {
...
Issue 4, Spring Security 的 authentication.isAuthenticated()不好使!明明沒登陸,為什么這個(gè)為true呢?
出錯(cuò)原因: 雖然你沒登陸,但是 anonymousUser 登陸了,這個(gè)時(shí)候你匿名能訪問的頁面里,也是 authenticated的!
解決方案:在thymeleaf里用spring4 dialect
1, Maven添加以下依賴:注意 3.0.2,RELEASE的 springsecurity4不支持3.0.2的thymeleaf,所以要指定version 為3.0.1.RELEASE.
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
2, 在頁面中用以下標(biāo)簽:
<div th:if="${#authentication.name == 'anonymousUser'}">請(qǐng)登陸</div>
這個(gè)辦法太挫,而且現(xiàn)在Spring Security 它 hardcode了anonymousUser,以后指不定用什么名字,于是山哥寫了一個(gè)工具類,拒絕hardcode!:
@Service
public class LoginUtil {
//Use this to get the Anonymous User name. Because do not want to hardcode.
private static AnonymousAuthenticationFilter anonymousAuthenticationFilter = new AnonymousAuthenticationFilter("internal_use");
public boolean isLogin(Authentication aut) {
if(aut == null || !aut.isAuthenticated()) {
return false;
} else
return !aut.getName().equals(anonymousAuthenticationFilter.getPrincipal());
}
}
待續(xù)……