基於SpringSecurity實現基於用戶名、密碼登錄及原理分析
SpringSecurity以一系列的過濾器鏈來進行權限的管理,可以自定義新的filter。
Demo實現
定義一個用戶,只有該用戶成功登陸 才能訪問接口,否則自動跳轉到登錄頁面
@Component
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 處理用戶獲取邏輯 UserDetailService
* 可以將獲取用戶信息的邏輯寫到loadUserByUserName中
* 處理用戶校驗邏輯 UserDetails
* User是UserDetails的實現 在這裏可以爲授權 即賦予當前用戶 xx角色
* 處理密碼加密解密 PasswordEncoder
*
* @param username
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//若填寫明文密碼,則默認的DaoAuthenticationProvider會進行校驗 會使用passwordEncoder進行匹配密碼,所以要指定一個passwordEncoder的Bean
return new User(username, passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
SpringSecurity的配置
@Configuration
@EnableWebSecurity
public class WebMvcSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//表單登錄 任何請求均進行認證
http.formLogin()
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
}
以上 即實現了一個簡單的基於用戶名、密碼的登錄校驗流程,只有登錄成功才能訪問接口或者直接訪問接口時會被攔截住,如果未被認證則跳轉到登錄頁面。
這裏的登錄頁是SpringSecurity默認自帶的
默認帶了兩種登錄方式,分別是formLogin/formBasic。兩者的區別只是交互方式有些不同。
原理分析
SpringSecurity主要由認證、授權兩個步驟組成。
先以UserDetailsService開始
/**
* 加載用戶特定數據的核心接口
* 它在整個框架中都作爲用戶DAO使用,並且是DaoAuthenticationProvider的策略
*
*/
public interface UserDetailsService {
/**
* 根據用戶名找到用戶。 在實際的實現中,根據實現實例的配置方式,搜索可能
* 區分大小寫或不區分大小寫。
* 在這種情況下,返回的 UserDetails 對象的用戶名可能與實際請求的用戶名不同。
*
* GrantedAuthority
*/
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
其中SpringSecurity中UserDetails接口的基本屬性含義如下:
- Authorities 授予用戶的權限 不能爲空
- password 認證用戶的密碼
- username 認證用戶的用戶名 不能爲空
- isAccountNonExpired 指明用戶的賬戶是否已經過期,過期賬戶不能爲認證
- isAccountNonLocked 指明用戶賬戶是否被鎖定,鎖定的賬戶不能被認證
- isCredentialsNonExpired 指示用戶的憑據(密碼)是否已過期。 已過期憑證阻止身份驗證
- isEnabled 指明用戶是啓用還是禁用。 禁用的用戶不能已驗證。
基於用戶名、密碼的登錄方式是由UserNamePasswordauthenticationFilter來處理的
UserNamePasswordAuthenticationFilter 監聽POST方式 默認路徑是/login的登錄方式
UserNamePasswordAuthenticationFilter類
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
其中this.getAuthenticationManager() 這裏是ProviderManager
ProviderManager
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
Class<? extends Authentication> toTest = authentication.getClass();
AuthenticationException lastException = null;
AuthenticationException parentException = null;
Authentication result = null;
Authentication parentResult = null;
boolean debug = logger.isDebugEnabled();
for (AuthenticationProvider provider : getProviders()) {
if (!provider.supports(toTest)) {
continue;
}
try {
result = provider.authenticate(authentication);
if (result != null) {
copyDetails(authentication, result);
break;
}
}
catch (AccountStatusException e) {
prepareException(e, authentication);
throw e;
}
catch (InternalAuthenticationServiceException e) {
prepareException(e, authentication);
throw e;
}
catch (AuthenticationException e) {
lastException = e;
}
}
if (result == null && parent != null) {
// Allow the parent to try.
try {
result = parentResult = parent.authenticate(authentication);
}
catch (ProviderNotFoundException e) {
}
catch (AuthenticationException e) {
lastException = parentException = e;
}
}
if (result != null) {
if (eraseCredentialsAfterAuthentication
&& (result instanceof CredentialsContainer)) {
((CredentialsContainer) result).eraseCredentials();
}
if (parentResult == null) {
eventPublisher.publishAuthenticationSuccess(result);
}
return result;
}
if (lastException == null) {
lastException = new ProviderNotFoundException(messages.getMessage(
"ProviderManager.providerNotFound",
new Object[] { toTest.getName() },
"No AuthenticationProvider found for {0}"));
}
prepareException(lastException, authentication);
}
throw lastException;
}
這裏,會從系統中存在的provider中輪詢符合要求的provider來進行認證操作。其中以supports方法返回true或false來判斷是否符合要求。
通過源碼發現,與用戶名、密碼登錄有關的provider是DaoAuthenticationProvider
我們可以先看下DaoAuthenticationProvider中supports方法
public boolean supports(Class<?> authentication) {
//這裏 只要認證的類是UsernamePasswordAuthenticationToken或UsernamePasswordAuthenticationToken的實現類
return (UsernamePasswordAuthenticationToken.class
.isAssignableFrom(authentication));
}
通過查看源碼發現,DaoAuthenticationProvider
關於認證的邏輯是在AbstractUserDetailsAuthenticationProvider
中
AbstractUserDetailsAuthenticationProvider
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
() -> messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.onlySupports",
"Only UsernamePasswordAuthenticationToken is supported"));
// Determine username
String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
: authentication.getName();
boolean cacheWasUsed = true;
UserDetails user = this.userCache.getUserFromCache(username);
if (user == null) {
cacheWasUsed = false;
try {
user = retrieveUser(username,
(UsernamePasswordAuthenticationToken) authentication);
}
catch (UsernameNotFoundException notFound) {
logger.debug("User '" + username + "' not found");
if (hideUserNotFoundExceptions) {
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
else {
throw notFound;
}
}
Assert.notNull(user,
"retrieveUser returned null - a violation of the interface contract");
}
try {
// 驗證用戶賬戶是否被鎖定、過期等
preAuthenticationChecks.check(user);
additionalAuthenticationChecks(user,
(UsernamePasswordAuthenticationToken) authentication);
}
catch (AuthenticationException exception) {
if (cacheWasUsed) {
cacheWasUsed = false;
user = retrieveUser(username,
(UsernamePasswordAuthenticationToken) authentication);
preAuthenticationChecks.check(user);
additionalAuthenticationChecks(user,
(UsernamePasswordAuthenticationToken) authentication);
}
else {
throw exception;
}
}
postAuthenticationChecks.check(user);
if (!cacheWasUsed) {
this.userCache.putUserInCache(user);
}
Object principalToReturn = user;
if (forcePrincipalAsString) {
principalToReturn = user.getUsername();
}
return createSuccessAuthentication(principalToReturn, authentication, user);
}
其中retrieveUser
/additionalAuthenticationChecks
等方法的實現是在其子類DaoAuthenticationProvider
中實現的
DaoAuthenticationProvider
protected final UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
prepareTimingAttackProtection();
try {
UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
return loadedUser;
}
catch (UsernameNotFoundException ex) {
mitigateAgainstTimingAttack(authentication);
throw ex;
}
catch (InternalAuthenticationServiceException ex) {
throw ex;
}
catch (Exception ex) {
throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
}
}
可以看到 這裏使用到了我們自定義MyUserDetailService#loadUserByUsername
認證完成之後,最終會將用戶信息封裝好 返回出去,過濾器繼續執行進入其他流程。
封裝用戶信息的方法在createSuccessAuthentication
中
protected Authentication createSuccessAuthentication(Object principal,
Authentication authentication, UserDetails user) {
//user.getAuthorities() 代表給登錄用戶授予的角色
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
principal, authentication.getCredentials(),
authoritiesMapper.mapAuthorities(user.getAuthorities()));
result.setDetails(authentication.getDetails());
return result;
}
獲取用戶的認證信息
直接調用SecurityContextHolder.getContext().getAuthentication()
或者把Authentication參數放到形參上
public Object getUser(Authentication authentication){
return authentication;
}
如果想要UserDetails信息,可以這樣做
public Object getUser(@AuthenticationPrincipal UserDetails user){
return user;
}
以上是最近學習SpringSecurity的心得,如有問題 請指出。