Spring Security 構建rest服務實現rememberme 記住我功能,restrememberme

來源:互聯網
上載者:User

Spring Security 構建rest服務實現rememberme 記住我功能,restrememberme

Spring security記住我基本原理:

登入的時候,請求發送給過濾器UsernamePasswordAuthenticationFilter,當該過濾器認證成功後,會調用RememberMeService,會產生一個token,將token寫入到瀏覽器cookie,同時RememberMeService裡邊還有個TokenRepository,將token和使用者資訊寫入到資料庫中。這樣當使用者再次訪問系統,訪問某一個介面時,會經過一個RememberMeAuthenticationFilter的過濾器,他會讀取cookie中的token,交給RememberService,RememberService會用TokenRepository根據token從資料庫中查是否有記錄,如果有記錄會把使用者名稱取出來,再調用UserDetailService根據使用者名稱擷取使用者資訊,然後放在SecurityContext裡。

 RememberMeAuthenticationFilter在Spring Security中認證過濾器鏈的倒數第二個過濾器位置,當其他認證過濾器都沒法認證成功的時候,就會調用RememberMeAuthenticationFilter嘗試認證。

實現:

 1,登入表單加上<input type="checkbox" name="remember-me" value="true"/>,SpringSecurity在SpringSessionRememberMeServices類裡定義了一個常量,預設值就是remember-me

 2,根據上邊的原理圖可知,要配置TokenRepository,把產生的token存進資料庫,這是一個配置bean的配置,放在了BrowserSecurityConfig裡

3,在configure裡配置

4,在BrowserProperties裡加上自動登入時間,把記住我時間做成可配置的

//記住我秒數配置private int rememberMeSeconds = 10;齊活package com.imooc.s@Configuration //這是一個配置public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{  //讀取使用者配置的登入頁配置  @Autowired  private SecurityProperties securityProperties;  //自訂的登入成功後的處理器  @Autowired  private AuthenticationSuccessHandler imoocAuthenticationSuccessHandler;  //自訂的認證失敗後的處理器  @Autowired  private AuthenticationFailureHandler imoocAuthenticationFailureHandler;  //資料來源  @Autowired  private DataSource dataSource;  @Autowired  private UserDetailsService userDetailsService;  //注意是org.springframework.security.crypto.password.PasswordEncoder  @Bean  public PasswordEncoder passwordencoder(){    //BCryptPasswordEncoder implements PasswordEncoder    return new BCryptPasswordEncoder();  }  /**   * 記住我TokenRepository配置,在登入成功後執行   * 登入成功後往資料庫存token的   * @Description: 記住我TokenRepository配置   * @param @return  JdbcTokenRepositoryImpl   * @return PersistentTokenRepository    * @throws   * @author lihaoyang   * @date 2018年3月5日   */  @Bean  public PersistentTokenRepository persistentTokenRepository(){    JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();    jdbcTokenRepository.setDataSource(dataSource);    //啟動時自動產生相應表,可以在JdbcTokenRepositoryImpl裡自己執行CREATE_TABLE_SQL指令碼產生表    jdbcTokenRepository.setCreateTableOnStartup(true);    return jdbcTokenRepository;  }  //版本二:可配置的登入頁  @Override  protected void configure(HttpSecurity http) throws Exception {    //驗證碼過濾器    ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();    //驗證碼過濾器中使用自己的錯誤處理    validateCodeFilter.setAuthenticationFailureHandler(imoocAuthenticationFailureHandler);    //配置的驗證碼過濾url    validateCodeFilter.setSecurityProperties(securityProperties);    validateCodeFilter.afterPropertiesSet();    //實現需要認證的介面跳轉表單登入,安全=認證+授權    //http.httpBasic() //這個就是預設的彈框認證    //    http //把驗證碼過濾器載入登入過濾器前邊      .addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)      //表單認證相關配置      .formLogin()         .loginPage("/authentication/require") //處理使用者認證BrowserSecurityController        //登入過濾器UsernamePasswordAuthenticationFilter預設登入的url是"/login",在這能改        .loginProcessingUrl("/authentication/form")         .successHandler(imoocAuthenticationSuccessHandler)//自訂的認證後處理器        .failureHandler(imoocAuthenticationFailureHandler) //登入失敗後的處理      .and()      //記住我相關配置        .rememberMe()        .tokenRepository(persistentTokenRepository())//TokenRepository,登入成功後往資料庫存token的        .tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())//記住我秒數        .userDetailsService(userDetailsService) //記住我成功後,調用userDetailsService查詢使用者資訊      .and()      //授權相關的配置       .authorizeRequests()         // /authentication/require:處理登入,securityProperties.getBrowser().getLoginPage():使用者配置的登入頁        .antMatchers("/authentication/require",        securityProperties.getBrowser().getLoginPage(),//放過登入頁不過濾,否則報錯        "/verifycode/image").permitAll() //驗證碼        .anyRequest()    //任何請求        .authenticated()  //都需要身份認證      .and()        .csrf().disable() //關閉csrf防護      ;    }}ecurity.browser;

其中由於要和資料庫打交道,所以需要注入一個資料來源:application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/imooc-demospring.datasource.username=rootspring.datasource.password=root

啟動應用,訪問 localhost:8080/user,需要登入

登入成功:

資料庫:產生一個persistent_logins表,存進去了一條資料

停止服務,從新啟動(注釋掉產生儲存token表的jdbcTokenRepository.setCreateTableOnStartup(true);)因為我們的使用者登入資訊都存在了session中,所以重啟服務後,再訪問localhost:8080/user,本應該重新引導到登入頁,但是由於配置了記住我,所以能夠直接存取,拿到了介面資料

要求標頭:

至此基本的rememberMe已做好

完整代碼放在了github:https://github.com/lhy1234/spring-security

總結

以上所述是小編給大家介紹的Spring Security 構建rest服務實現rememberme 記住我功能,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.