Java安全框架(一)Spring Security


文章主要分三部分
1、Spring Security的架構及核心組件:(1)認證;(2)權限攔截;(3)數據庫管理;(4)權限緩存;(5)自定義決策;
2、環境搭建與使用,使用當前熱門的Spring Boot來搭建環境,結合項目中實際的例子來做幾個Case;
3、Spring Security的優缺點總結,結合第二部分中幾個Case的實現來總結Spring Security的優點和缺點。

1、Spring Security介紹

​ 整體介紹,Spring Security為基於J2EE開發的企業應用軟件提供了全面的安全服務,特別是使用Spring開發的企業軟件項目,如果你熟悉Spring,尤其是Spring的依賴注入原理,這將幫助你更快掌握Spring Security,目前使用Spring Security有很多原因,通常因為在J2EE的Servlet規范和EJB規范中找不到典型應用場景的解決方案,提到這些規范,特別要指出的是它們不能在WAR或EAR級別進行移植,這樣如果你需要更換服務器環境,就要在新的目標環境中進行大量的工作,對你的應用進行重新配置安全,使用Spring Security就解決了這些問題,也為你提供了很多很有用的可定制的安全特性。
​ Spring Security包含三個主要的組件:SecurityContextAuthenticationManagerAccessDecisionManager.

Spring Security主要組件圖
圖1-1 Spring Security主要組件

1.1 認證

​ Spring Security提供了很多過濾器,它們攔截Servlet請求,並將這些請求轉交給認證處理過濾器和訪問決策過濾器進行處理,並強制安全性認證用戶身份和用戶權限以達到保護WEB資源的目的,Spring Security安全機制包括兩個主要的操作,認證驗證,驗證也可以稱為權限控制,這是Spring Security兩個主要的方向,認證是為用戶建立一個他所聲明的主體的過程,這個主體一般是指用戶設備或可以在系統中執行行動的其他系統,驗證指用戶能否在應用中執行某個操作,在到達授權判斷之前身份的主體已經由身份認證過程建立了。下面列出幾種常用認證模式,這里不對它們作詳細介紹,需要詳細了解的老鐵們可以自行查查對應的資料。

  1. BasicHTTP1.0提出,一種基於challenge/response的認證模式,針對特定的realm需要提供用戶名和密碼認證后才可訪問,其中密碼使用明文傳輸。缺點:①無狀態導致每次通信都要帶上認證信息,即使是已經認證過的資源;②傳輸安全性不足,認證信息用Base64編碼,基本就是明文傳輸,很容易對報文截取並盜用認證信息。
  2. DigestHTTP1.1提出,它主要是為了解決Basic模式安全問題,用於替代原來的Basic認證模式,Digest認證也是采用challenge/response認證模式,基本的認證流程比較類似。Digest模式避免了密碼在網絡上明文傳輸,提高了安全性,但它仍然存在缺點,例如認證報文被攻擊者攔截到攻擊者可以獲取到資源。
  3. X.509:證書認證,X.509是一種非常通用的證書格式,證書包含版本號、序列號(唯一)、簽名、頒發者、有效期、主體、主體公鑰。
  4. LDAP:輕量級目錄訪問協議(Lightweight Directory Access Protocol)。
  5. Form:基於表單的認證模式。

1.2 權限攔截

image-20201024122405276
圖1-2 用戶請求
圖1-3 過濾器

​ Spring Security提供了很多過濾器,其中SecurityContextPersistenceFilterUsernamePasswordAuthenticationFilterFilterSecurityInterceptor分別對應SecurityContextAuthenticationManagerAccessDecisionManager的處理。

Spring Security過濾鏈流程圖
圖1-4 Spring Security過濾鏈流程圖

下面分別介紹各個過濾器的功能。

過濾器 描述
WebAsyncManagerIntegrationFilter 設置SecurityContext到異步線程中,用於獲取用戶上下文信息
SecurityContextPersistenceFilter 整個請求過程中SecurityContext的創建和清理
1.未登錄,SecurityContext為null,創建一個新的ThreadLocalSecurityContext填充SecurityContextHolder.
2.已登錄,從SecurityContextRepository獲取的SecurityContext對象.
兩個請求完成后都清空SecurityContextHolder,並更新SecurityContextRepository
HeaderWriterFilter 添加頭信息到響應對象
CsrfFilter 防止csrf攻擊(跨站請求偽造)的過濾器
LogoutFilter 登出處理
UsernamePasswordAuthenticationFilter 獲取表單用戶名和密碼,處理基於表單的登錄請求
DefaultLoginPageGeneratingFilter 配置登錄頁面
BasicAuthenticationFilter 檢測和處理http basic認證,將結果放進SecurityContextHolder
RequestCacheAwareFilter 處理請求request的緩存
SecurityContextHolderAwareRequestFilter 包裝請求request,便於訪問SecurityContextHolder
AnonymousAuthenticationFilter 匿名身份過濾器,不存在用戶信息時調用該過濾器
SessionManagementFilter 檢測有用戶登錄認證時做相應的session管理
ExceptionTranslationFilter 處理AccessDeniedException訪問異常和AuthenticationException認證異常
FilterSecurityInterceptor 檢測用戶是否具有訪問資源路徑的權限

1.3 數據庫管理

Spring Security核心處理流程
圖1-5 Spring Security核心處理流程

​ 上圖展示的Spring Security核心處理流程。當一個用戶登錄時,會先進行身份認證,如果身份認證未通過會要求用戶重新認證,當用戶身份證通過后就會調用角色管理器判斷他是否可以訪問,這里,如果要實現數據庫管理用戶及權限,就需要自定義用戶登錄功能,Spring Security已經提供好了一個接口UserDetailsService

package org.springframework.security.core.userdetails;

public interface UserDetailsService {
	
	/**
	 * 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;
    
}

UserDetailService該接口只有一個方法,通過方法名可以看出方法是通過用戶名來獲取用戶信息的,但返回結果是UserDetails對象,UserDetails也是一個接口,接口中任何一個方法返回false用戶的憑證就會被視為無效。

package org.springframework.security.core.userdetails;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;
import java.util.Collection;

/**
 * Provides core user information.
 *
 * <p>
 * Implementations are not used directly by Spring Security for security purposes. They
 * simply store user information which is later encapsulated into {@link Authentication}
 * objects. This allows non-security related user information (such as email addresses,
 * telephone numbers etc) to be stored in a convenient location.
 * <p>
 * Concrete implementations must take particular care to ensure the non-null contract
 * detailed for each method is enforced. See
 * {@link org.springframework.security.core.userdetails.User} for a reference
 * implementation (which you might like to extend or use in your code).
 *
 * @see UserDetailsService
 * @see UserCache
 *
 * @author Ben Alex
 */
public interface UserDetails extends Serializable {
	// ~ Methods
	// ========================================================================================================

	/**
	 * Returns the authorities granted to the user. Cannot return <code>null</code>.
	 *
	 * @return the authorities, sorted by natural key (never <code>null</code>)
	 */
	Collection<? extends GrantedAuthority> getAuthorities(); //權限集合

	/**
	 * Returns the password used to authenticate the user.
	 *
	 * @return the password
	 */
	String getPassword(); //密碼

	/**
	 * Returns the username used to authenticate the user. Cannot return <code>null</code>.
	 *
	 * @return the username (never <code>null</code>)
	 */
	String getUsername(); //用戶名

	/**
	 * Indicates whether the user's account has expired. An expired account cannot be
	 * authenticated.
	 *
	 * @return <code>true</code> if the user's account is valid (ie non-expired),
	 * <code>false</code> if no longer valid (ie expired)
	 */
	boolean isAccountNonExpired(); //賬戶是否過期

	/**
	 * Indicates whether the user is locked or unlocked. A locked user cannot be
	 * authenticated.
	 *
	 * @return <code>true</code> if the user is not locked, <code>false</code> otherwise
	 */
	boolean isAccountNonLocked(); //賬戶是否被鎖定

	/**
	 * Indicates whether the user's credentials (password) has expired. Expired
	 * credentials prevent authentication.
	 *
	 * @return <code>true</code> if the user's credentials are valid (ie non-expired),
	 * <code>false</code> if no longer valid (ie expired)
	 */
	boolean isCredentialsNonExpired(); //證書是否過期

	/**
	 * Indicates whether the user is enabled or disabled. A disabled user cannot be
	 * authenticated.
	 *
	 * @return <code>true</code> if the user is enabled, <code>false</code> otherwise
	 */
	boolean isEnabled(); //賬戶是否有效
}

​ 這里需要注意的是AuthenticationUserDetails對象的區分,Authentication對象才是Spring Security使用的進行安全訪問控制用戶信息的安全對象,實際上Authentication對象有未認證和已認證兩種狀態,在作為參數傳入認證管理器的時候,它是一個為認證的對象,它從客戶端獲取用戶的身份認證信息,如用戶名、密碼,可以是從一個登錄頁面,也可以是從cookie中獲取,並由系統自動生成一個Authentication對象,而這里的UserDetails代表的是一個用戶安全信息的源,這個源可以是從數據庫、LDAP服務器、CA中心返回,Spring Security要做的就是將未認證的Authentication對象與UserDetails對象進行匹配,成功后將UserDetails對象中的權限信息拷貝到Authentication中,組成一個完整的Authentication對象,與其他組件進行共享。

package org.springframework.security.core;

import java.io.Serializable;
import java.security.Principal;
import java.util.Collection;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;

public interface Authentication extends Principal, Serializable {

    /**權限集合*/
	Collection<? extends GrantedAuthority> getAuthorities();

	/**獲取憑證*/
	Object getCredentials();

	/**獲取認證一些額外信息*/
	Object getDetails();

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

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

	/**
	 * See {@link #isAuthenticated()} for a full description.
	 * <p>
	 * Implementations should <b>always</b> allow this method to be called with a
	 * <code>false</code> parameter, as this is used by various classes to specify the
	 * authentication token should not be trusted. If an implementation wishes to reject
	 * an invocation with a <code>true</code> parameter (which would indicate the
	 * authentication token is trusted - a potential security risk) the implementation
	 * should throw an {@link IllegalArgumentException}.
	 *
	 * @param isAuthenticated <code>true</code> if the token should be trusted (which may
	 * result in an exception) or <code>false</code> if the token should not be trusted
	 *
	 * @throws IllegalArgumentException if an attempt to make the authentication token
	 * trusted (by passing <code>true</code> as the argument) is rejected due to the
	 * implementation being immutable or implementing its own alternative approach to
	 * {@link #isAuthenticated()}
	 */
	void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
}

​ 了解了Spring Security的上面三個對象,當我們需要數據庫管理用戶時,我們需要手動實現UserDetailsService對象中的loadUserByUsername方法,這就需要我們同時准備以下幾張數據表,分別是用戶表(user)、角色表(role)、權限表(permission)、用戶和角色關系表(user_role)、權限和角色關系表(permission_role),UserDetails中的用戶狀態通過用戶表里的屬性去填充,UserDetails中的權限集合則是通過角色表、權限表、用戶和角色關系表、權限和角色關系表構成的RBAC模型來提供,這樣就可以把用戶認證、用戶權限集合放在數據庫中進行管理了。

1.4 權限緩存

​ Spring Security的權限緩存和數據庫管理有關,都是在用戶認證上做文章,所以都與UserDetails有關,與數據庫管理不同的是,Spring Security提供了一個可以緩存UserDetailsService的實現類,這個類的名字是CachingUserDetailsService

package org.springframework.security.authentication;

import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.util.Assert;

/**
 *
 * @author Luke Taylor
 * @since 2.0
 */
public class CachingUserDetailsService implements UserDetailsService {
	private UserCache userCache = new NullUserCache();
	private final UserDetailsService delegate;

	public CachingUserDetailsService(UserDetailsService delegate) {
		this.delegate = delegate;
	}

	public UserCache getUserCache() {
		return userCache;
	}

	public void setUserCache(UserCache userCache) {
		this.userCache = userCache;
	}

	public UserDetails loadUserByUsername(String username) {
		UserDetails user = userCache.getUserFromCache(username);
		//緩存中不存在UserDetails時,通過UserDetailsService加載
		if (user == null) {
			user = delegate.loadUserByUsername(username);
		}

		Assert.notNull(user, () -> "UserDetailsService " + delegate
				+ " returned null for username " + username + ". "
				+ "This is an interface contract violation");
		//將UserDetials存入緩存,並將UserDetails返回
		userCache.putUserInCache(user);
		return user;
	}
}

CachingUserDetailsService類的構造接收一個用於真正加載UserDetailsUserDetailsService實現類,當需要加載UserDetails時,會首先從緩存中獲取,如果緩存中沒有UserDetails存在,則使用持有的UserDetailsService實現類進行加載,然后將加載后的結果存在緩存中,UserDetails與緩存的交互是通過UserCache接口來實現的,CachingUserDetailsService默認擁有一個UserCacheNullUserCache()實現。Spring Security提供的緩存都是基於內存的緩存,並且緩存的UserDetails對象,在實際應用中一般會用到更多的緩存,比如Redis,同時也會對權限相關的信息等更多的數據進行緩存。

2.5 自定義決策

​ Spring Security在用戶身份認證通過后,會調用一個角色管理器判斷是否可以繼續訪問,[Spring Security核心處理流程(圖1-5)](#1.3 數據庫管理)中的AccessDecisionManager就是Spring Security的角色管理器,它對應的抽象類為AbstractAccessDecisionManager,要自定義決策管理器的話一般是繼承這個抽象類,而不是去實現接口。

package org.springframework.security.access.vote;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;

/**
 * Abstract implementation of {@link AccessDecisionManager}.
 *
 * <p>
 * Handles configuration of a bean context defined list of {@link AccessDecisionVoter}s
 * and the access control behaviour if all voters abstain from voting (defaults to deny
 * access).
 */
public abstract class AbstractAccessDecisionManager implements AccessDecisionManager,
		InitializingBean, MessageSourceAware {
	protected final Log logger = LogFactory.getLog(getClass());

	private List<AccessDecisionVoter<?>> decisionVoters;

	protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

	private boolean allowIfAllAbstainDecisions = false;

	protected AbstractAccessDecisionManager(
			List<AccessDecisionVoter<?>> decisionVoters) {
		Assert.notEmpty(decisionVoters, "A list of AccessDecisionVoters is required");
		this.decisionVoters = decisionVoters;
	}

	public void afterPropertiesSet() {
		Assert.notEmpty(this.decisionVoters, "A list of AccessDecisionVoters is required");
		Assert.notNull(this.messages, "A message source must be set");
	}

	protected final void checkAllowIfAllAbstainDecisions() {
		if (!this.isAllowIfAllAbstainDecisions()) {
			throw new AccessDeniedException(messages.getMessage(
					"AbstractAccessDecisionManager.accessDenied", "Access is denied"));
		}
	}

	public List<AccessDecisionVoter<?>> getDecisionVoters() {
		return this.decisionVoters;
	}

	public boolean isAllowIfAllAbstainDecisions() {
		return allowIfAllAbstainDecisions;
	}

	public void setAllowIfAllAbstainDecisions(boolean allowIfAllAbstainDecisions) {
		this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions;
	}

	public void setMessageSource(MessageSource messageSource) {
		this.messages = new MessageSourceAccessor(messageSource);
	}

	public boolean supports(ConfigAttribute attribute) {
		for (AccessDecisionVoter voter : this.decisionVoters) {
			if (voter.supports(attribute)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Iterates through all <code>AccessDecisionVoter</code>s and ensures each can support
	 * the presented class.
	 * <p>
	 * If one or more voters cannot support the presented class, <code>false</code> is
	 * returned.
	 *
	 * @param clazz the type of secured object being presented
	 * @return true if this type is supported
	 */
	public boolean supports(Class<?> clazz) {
		for (AccessDecisionVoter voter : this.decisionVoters) {
			if (!voter.supports(clazz)) {
				return false;
			}
		}
		return true;
	}
}

​ 里面的核心方法是supports方法,方法中用到一個decisionVoters的集合,集合中的類型是AccessDecisionVoter,這是Spring Security引入的一個投票器,有無權限訪問的最終決定權就是由投票器來決定的。

package org.springframework.security.access;

import java.util.Collection;

import org.springframework.security.core.Authentication;

public interface AccessDecisionVoter<S> {
	int ACCESS_GRANTED = 1;
	int ACCESS_ABSTAIN = 0;
	int ACCESS_DENIED = -1;

	boolean supports(ConfigAttribute attribute);

	boolean supports(Class<?> clazz);

	int vote(Authentication authentication, S object,
			Collection<ConfigAttribute> attributes);
}

​ 這里有很多投票器,最常見的為RoleVoter投票器,RoleVoter定義了權限的前綴"ROLE_",投票器的核心是靠vote這個選舉方法來實現的,方法中的參數authentication是用戶及權限信息,attributes是訪問資源需要的權限,代碼里循環判斷用戶是否有訪問資源需要的權限,如果有就返回ACCESS_GRANTED,即有權限。

package org.springframework.security.access.vote;

import java.util.Collection;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

public class RoleVoter implements AccessDecisionVoter<Object> {

   private String rolePrefix = "ROLE_";

   public String getRolePrefix() {
      return rolePrefix;
   }

   public void setRolePrefix(String rolePrefix) {
      this.rolePrefix = rolePrefix;
   }

   public boolean supports(ConfigAttribute attribute) {
      if ((attribute.getAttribute() != null)
            && attribute.getAttribute().startsWith(getRolePrefix())) {
         return true;
      }
      else {
         return false;
      }
   }

   public boolean supports(Class<?> clazz) {
      return true;
   }
   
   /**
   * authentication是用戶及權限信息
   * attributes是訪問資源需要的權限
   */
   public int vote(Authentication authentication, Object object,
         Collection<ConfigAttribute> attributes) {
      if (authentication == null) {
         return ACCESS_DENIED;
      }
      int result = ACCESS_ABSTAIN;
      Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);

      for (ConfigAttribute attribute : attributes) {
         if (this.supports(attribute)) {
            result = ACCESS_DENIED;

            // Attempt to find a matching granted authority
            for (GrantedAuthority authority : authorities) {
               if (attribute.getAttribute().equals(authority.getAuthority())) {
                  return ACCESS_GRANTED;
               }
            }
         }
      }

      return result;
   }
   Collection<? extends GrantedAuthority> extractAuthorities(
         Authentication authentication) {
      return authentication.getAuthorities();
   }
}

​ Spring Seucrity提供了三種投票決策,分別是AffirmativeBased:一票通過即可訪問;ConsensusBased:一半以上通過才允許訪問;UnanimousBased:全部通過才允許訪問。自定義決策只需要繼承AbstractAccessDecisionManager抽象類,可以自定義自己的投票器,比如需要同時滿足多個條件才能訪問等,不需要使用Spring Security自帶的投票器。

2、環境搭建及使用

2.1 快速搭建Spring Boot + Spring Security環境

​ 打開Spring Boot官網https://start.spring.io/,選擇Java語言,在Dependencies中添加Spring Web和Spring Security,最后點擊GENERATE下載。

​ 解壓下載的文件,用idea打開,可以看到這是一個可以直接啟動的demo,因為我們是web項目,所以這里添加一個接口看一下。

@SpringBootApplication
@RestController
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @RequestMapping("/")
   public String home() {
      return "hello spring boot";
   }
}

​ 啟動后我們在地址欄輸入locahost:8080會自動跳轉到/login路徑,說明Spring Security就已經直接參與進來了。

​ 然后我們創建一個繼承WebSecurityConfigurerAdapter的配置類,定義權限訪問策略,同時再添加一個路徑為“/hello”的接口,根據代碼注釋我們可以看出,訪問項目主路徑可以不需要驗證,訪問其余路徑則需要驗證。啟動項目,訪問localhost:8080可以直接通過,但訪問localhost:8080\hello則會自動跳轉到localhost:8080/login路徑要求登錄。這樣說明Spring Security的安全策略已經生效了,Spring Boot與Spring Security的環境搭建也完成了。

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 攔截策略
     * 定義哪些路徑需要被攔截,哪些路徑不需要攔截
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll() //項目主路徑可以放行
                .anyRequest().authenticated() //其余所有請求需要驗證
                .and().logout().permitAll() //允許登出可以訪問
                .and().formLogin(); //允許表單登錄
        http.csrf().disable(); //關閉csrf認證
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        /**
         * 忽略靜態資源的攔截
         */
        web.ignoring().antMatchers("/js/**", "/css/**");
    }
}

2.2 常用Case實現

2.2.1 只要能登錄即可

​ 只要登錄就可以訪問項目所有資源路徑,也不用寫單獨的登錄頁面,這里就會用到Spring Security提供的基於內存的驗證。在SpringSecurityConfig類中繼續重寫configure(AuthenticationManagerBuilder auth)這個方法。Spring security 5.0之后新增了多種加密方式,改變了默認的密碼格式,新的密碼存儲格式是“{id}…………”.前面的id是加密方式,id可以是bcrypt、sha256等,后面跟着的是加密后的密碼。也就是說,程序拿到傳過來的密碼的時候,會首先查找被“{”和“}”包括起來的id,來確定后面的密碼是被怎么樣加密的,如果找不到就認為id是null。這時候程序會報錯:There is no PasswordEncoder mapped for the id “null”.實際應用中也可以自定義加密方式,只需要繼承PasswordEncoder接口即可。

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //創建一個用戶名為admin,密碼為123456,角色為ADMIN的用戶
       auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("ADMIN");

        //可指定多個用戶
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("DEMO");
    }
}

2.2.2 有指定的角色,每個角色有指定的權限

​ 添加一個限定角色的請求,需要有ADMIN角色的才能訪問,“ROLE_”為RoleVoter中定義的前綴,在前面自定義決策中提到過。同時,這里還需要注意的是,使用@PreAuthorize這個注解時,一定要在類上加上@EnableGlobalMethodSecurity(prePostEnabled = true)注解@PreAuthorize才會生效。這樣admin用戶就可以訪問/roleAuth,但zhangsan則不可以訪問/roleAuth。

@SpringBootApplication
@RestController
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DemoApplication {
    /**中間代碼省略**/
    
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping("/roleAuth")
	public String role() {
		return "admin auth";
	}
}

​ 實際場景中用戶角色一般是存儲在數據庫中的,前面提到過Spring Security的數據庫管理需要實現UserDetailsService接口,定義數據庫相關查詢,返回UserDetails對象。

package com.mall.demo;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class MyUserService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return null;
    }
}
@Autowired
private MyUserService myUserService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(myUserService);
    /**
     * Spring Security提供的默認數據庫驗證
     */
    auth.jdbcAuthentication()
            .usersByUsernameQuery("") //查詢users
            .authoritiesByUsernameQuery(""); //查詢權限
}

​ 數據庫管理在實際項目能更好的說明,這里我們回到Spring Security權限配置,之前使用過@PreAuthorize這個注解來控制方法是否能被調用,實際上Spring Security提供了4個這樣的注解,分別是@PreAuthorize@PostAuthorize@PreFilter@PostFilter@PreAuthorize@PostAuthorize的作用分別是在方法調用前和調用后對權限進行檢查,@PreFilter@PostFilter的作用是對集合類的參數或返回值進行過濾。

//傳入的id參數小於10
//傳入的username=當前用戶名
//傳入的User對象的用戶名=zhangsan
@PreAuthorize("#id<10 and principal.username.equals(#username) and #user.username.equals('zhangsan')")
//驗證返回結果是否是偶數
@PostAuthorize("returnObject%2==0")
@RequestMapping("/test1")
public Integer test1(Integer id, String username, User user) {
   return id;
}

//過濾傳入的參數保留偶數
@PreFilter("filterObject%2==0")
//過濾返回結果保留被4整除的數
@PostFilter("filterObject%4==0")
@RequestMapping("/test2")
public List<Integer> test2(List<Integer> idList) {
   return idList;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM