1. 程式人生 > >5. Spring Boot + Spring Security 記住我功能

5. Spring Boot + Spring Security 記住我功能

人理解:整合spring security框架,只需要簡單的配置即可 基本流程: 瀏覽器認證使用者名稱密碼請求,認證成功後,有一個TOkenRepository 來儲存使用者名稱和密碼,並且儲存到自動的資料庫中,下次使用者再規定時間內登陸使用者就直接從記住過濾器中讀取Cookie中的Token使用者名稱,然後通過通過T歐肯Repository 使用者名稱去訪問DB 資料庫,並判斷是否跟資料庫中的資料是否一致,並且返回UserDetailsService

在這裡插入圖片描述

  1. 設定記住我在這裡插入圖片描述的過期時間為一天, 在這裡插入圖片描述
  2. 配置檔案BrowserSecurityConfig.java 在這裡插入圖片描述
protected void configure(HttpSecurity http) throws Exception {
		
		ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
		validateCodeFilter.setAuthenticationFailureHandler(imoccAuthenticationFailUrlHandler);
		validateCodeFilter.setSecurityProperties(securityProperties);
		validateCodeFilter.afterPropertiesSet();
		
		http.addFilterBefore(validateCodeFilter,UsernamePasswordAuthenticationFilter.class)//validatecodeFilter過濾器載入到使用者名稱密碼過濾器校驗的前面
		    .formLogin()//表單認證
			.loginPage("/authentication/require")//新增自定義登陸介面
			.loginProcessingUrl("/authentication/from")//這個URL用UsernamePasswordAuthenticationFilter來處理
			.successHandler(imoccAuthenticationSuccessHandler)
			.failureHandler(imoccAuthenticationFailUrlHandler)
			.and()
		//配置記住我
			.rememberMe()
			.tokenRepository(persistentTokenRepository())
			.tokenValiditySeconds(securityProperties.getBrowser().getRemeberMeSeconds())
			.userDetailsService(userDetailsService)
		//http.httpBasic()//彈出框認證
			.and()
			.authorizeRequests()//對請求做一個授權
			.antMatchers("/authentication/require"
					,securityProperties.getBrowser().getLoginPage()
					,"/code/image").permitAll()//訪問這個頁面的時候不需要授權
			.anyRequest()//任何請求
			.authenticated()//身份認證
			.and()
			.csrf().disable();//關閉跨站請求偽造
	}