1. 程式人生 > >Spring Security學習筆記-資料庫管理

Spring Security學習筆記-資料庫管理

Spring Security-資料庫管理

  當一個使用者登陸時,會先執行身份認證,如果身份認證未通過則會要求使用者重新認證;當用戶身份認證通過後,則會呼叫角色管理器,判斷使用者是否可以訪問。這裡,如果要實現使用資料庫管理使用者及許可權,就需要自定義使用者登陸功能,而SpringSecurity已經為我們提供好了介面。

public interface UserDetailsService {
   // ~ Methods
   // =========================================================================
/** * Locates the user based on the username. In the actual implementation, the search * may possibly be case sensitive, or case insensitive depending on how the * implementation instance is configured. In this case, the <code>UserDetails</code> * object that comes back may have a username that is of a different case than what * was actually requested.. * * @param username the username identifying the user whose data is required. * * @return a fully populated user record (never <code>null</code>) * * @throws UsernameNotFoundException if the user could not be found or the user has no * GrantedAuthority */
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; }

  UserServiceDetails只有一個方法loadUserByUsername,根據方法名可以初步判斷功能為根據使用者名稱返回使用者資訊,而它的返回值也是一個介面。

public interface UserDetails extends Serializable {
	// ~ Methods
	// =========================================================================
* Returns the authorities granted to the user. Cannot return <code>null</code>. Collection<? extends GrantedAuthority> getAuthorities();//許可權集合,儲存了使用者所有的許可權 String getPassword(); String getUsername(); boolean isAccountNonExpired();//賬戶是否過期 boolean isAccountNonLocked();//賬戶是否被鎖定 boolean isCredentialsNonExpired();//證書時候過期 boolean isEnabled();//賬戶是否有效 }

  其中後四個判斷方法,任何一個返回false,則使用者被視為無效。注意Authentication和UserDetails的區分,Authentication物件才是SpringSecurity使用的進行安全訪問控制使用者資訊的安全物件,實際上Authentication物件有未認證和已認證的兩種狀態,在作為引數傳入認證管理器的時候,它是一個未認證的物件,它從客戶端獲取使用者的身份資訊,如使用者名稱密碼,可以是從一個登陸頁面也可以是從cookie中獲取,並由系統自動構成一個Authentication物件。而上面的UserDetails它代表的是一個使用者安全資訊的源,這個源可以是從資料庫,LDAP伺服器,CA中心返回。SpringSecurity要做的就是將等待認證的Authentication物件和UserDetails物件進行匹配,成功後,將UserDetails中的使用者資訊拷貝到Authentication中,組成一個完整的Authentication物件與其他元件進行共享。UserDetails既可以從資料庫中返回,也可以LDAP等中返回,這取決與系統中使用什麼來儲存使用者資訊和許可權以及相應的使用者提供者。

public interface Authentication extends Principal, Serializable {
	// ~ Methods
================================================================================================

	Collection<? extends GrantedAuthority> getAuthorities();//許可權集合

	Object getCredentials();//獲取憑證

	Object getDetails();//獲取認證一些額外資訊

	Object getPrincipal();//過去認證的實體

	boolean isAuthenticated();//是否認證通過

	void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
}

  當我們需要使用資料庫管理使用者時,我們需要手動實現UserDetailsService接口裡面的loadUserByUsername方法,這就需要準備一下幾張表。它們分別是使用者表,角色表,許可權表,使用者和角色關係表,許可權和角色關係表。UserDetails中的使用者狀態通過使用者表裡的屬性去填充,UserDetails中的許可權集合則是通過使用者表,許可權表,使用者和角色關係表,許可權和角色關係表構成的RBAC模型來提供。