Security 就是安全機制,安全機制的核心則是存取權限的設定。以下依據官方文件,整理用戶登入的三種配置方式。
<authentication-manager>
<authentication-provider>
<user-service>
<user name="jimi" password="jimispassword"
authorities="ROLE_USER, ROLE_ADMIN" />
<user name="bob" password="bobspassword"
authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
適合快速驗證環境,上 production 當然不能這樣。
<authentication-manager>
<authentication-provider>
<user-service id="userDetailsService"
properties="classpath:user.properties"/>
</authentication-provider>
</authentication-manager>
檔內容格式為:
username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]
例如:
jimi=jimispassword,ROLE_USER,ROLE_ADMIN,enabled bob=bobspassword,ROLE_USER,enabled
我照文件敲的時候碰到一個錯誤:properties 屬性指定檔案時,classpath: 前綴不能省,否則必須給出明確的絕對路徑,兩者擇一。
做法一是引用外部已定義的資料來源:
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="securityDataSource"/>
</authentication-provider>
</authentication-manager>
其中 securityDataSource 就是 applicationContext 中配置的那個資料來源。
做法二是直接在 security 設定檔裡宣告 Bean:
<authentication-manager>
<authentication-provider user-service-ref='myUserDetailsService'/>
</authentication-manager>
<b:bean id="myUserDetailsService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<b:property name="dataSource" ref="dataS"/>
</b:bean>
文件給出的預設表如下(不同資料庫語法略有差異,稍作調整即可):
create table users(
username varchar_ignorecase(50) not null primary key,
password varchar_ignorecase(50) not null,
enabled boolean not null);
create table authorities (
username varchar_ignorecase(50) not null,
authority varchar_ignorecase(50) not null,
constraint fk_authorities_users foreign key(username) references users(username));
create unique index ix_auth_username on authorities (username, authority);
三種方式其實對應三個階段:先用記憶體跑通流程,再用 properties 檔把帳號外置,最後接到資料庫並搭配自訂的 UserDetailsService 擴充查詢邏輯。若表結構無法配合框架預設,實作 UserDetailsService 介面自行封裝,通常比硬改 SQL 來得乾淨。