Spring Security是一個為企業應用系統提供聲明式的安全訪問控制功能,減少為了企業應用系統安全控制而編寫的大量重復代碼。
認證:
spring security的原理就是使用很多的攔截器對URL進行攔截,以此來管理用戶登錄和授權,用戶登錄時,會被AuthenticationProcessingFilter攔截,通過ProviderManager來對用戶信息進行驗證,如果驗證通過后會將用戶的權限信息封裝成User放到SecurityContextHolder中,以備后面訪問資源時使用。
我們要自定義用戶的校驗機制的話,只要實現AuthenticationProvider,將他注入到配置類中
授權:
基於RBAC的權限控制,RBAC一般都是由 3個部分組成,用戶,角色 ,資源(菜單,按鈕),然后就是用戶和角色的關聯表,角色和資源的關聯表,核心就是判斷當前用戶所擁有的URL是否和當前訪問的URL是否匹配
Spring Security配置
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationProvider provider; @Autowired private AuthenticationSuccessHandler myAuthenticationSuccessHandler; @Autowired private AuthenticationFailureHandler myAuthenticationFailHander; //注入我們自己的AuthenticationProvider @Override protected void configure(HttpSecurity http) throws Exception { http //表示表單登錄的url是/login,表單提交的url是/login/form //myAuthenticationSuccessHandler 登錄成功處理器 //myAuthenticationFailHander 登錄失敗處理器 .formLogin().loginPage("/login").loginProcessingUrl("/login/form") .successHandler(myAuthenticationSuccessHandler) .failureHandler(myAuthenticationFailHander) .permitAll() //permitAll()表示允許訪問/login,/login/form .and() //設置授權請求,任何請求都要經過下面的權限表達式處理 .authorizeRequests() .anyRequest().access("@rbacService.hasPermission(request,authentication)") //權限表達式 .and() //在Security的默認攔截器里,默認會開啟CSRF處理,判斷請求是否攜帶了token,如果沒有就拒絕訪問,所以這里要關閉CSRF處理 .csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(provider); } }
github下載地址:https://github.com/jake1263/SpringSecurity