봄 보안 내 기본 원칙을 기억하십시오.
로그인하면 요청이 필터 usernamepasswordauthenticationFilter로 전송됩니다. 필터가 성공적으로 인증되면 Token을 생성하고 Token을 브라우저 쿠키에 작성하는 Rememservice가 호출됩니다. 동시에 RememberMeservice에는 토큰 및 사용자 정보를 데이터베이스에 쓰는 토큰 레피터가 있습니다. 이런 식으로 사용자가 시스템에 다시 액세스하고 인터페이스에 액세스하면 RememberMeauthenticationFilter 필터를 통과합니다. 그것은 쿠키의 토큰을 읽고 그것을 기억하십시오. Rememberservice는 TokenRepository를 사용하여 토큰을 기반으로 데이터베이스의 레코드가 있는지 확인합니다. 레코드가 있으면 사용자 이름이 꺼진 다음 userDetailService에 전화하여 사용자 이름을 기반으로 사용자 정보를 얻은 다음 SecurityContext에 넣습니다.
RememberMeAuthenticationFilter 스프링 보안에서 필터 체인의 두 번째 라이트 필터 위치를 인증합니다. 다른 인증 필터를 성공적으로 인증 할 수없는 경우, 인증을 시도하기 위해 MeauthenticationFilter가 호출됩니다.
성취하다:
1. add <input type="checkbox" name="remember-me" value="true"/> 로그인 양식에 Springsecurity는 SpringSessionRememberMeServices 클래스에서 상수를 정의하며 기본값은 기억됩니다.
2. 위의 회로도에 따르면, 토큰 레피 성을 구성하고 생성 된 토큰을 데이터베이스에 저장해야합니다. 구성 Bean 구성이며 BrowserseCurityConfig에 배치되었습니다.
3. 구성에서 구성
4. BrowserProperties에 자동 로그인 시간을 추가하여 구성 가능하게 만듭니다.
// private int regemeseconds = 10; qihuo 패키지 com.imooc.s@configuration // 이것은 구성 공개 클래스 BrowserseCurityConfig를 확장하는 구성입니다. websecurityConfigurerAdapter {// 사용자 구성의 로그인 페이지 구성 @autow private securityProperTies SecurityProperTies; // 성공적인 로그인 후 사용자 정의 된 프로세서 @autowired private authenticationsuccesshandler imoocauthenticationsuccesshandler; // 인증에 실패한 후 사용자 정의 된 프로세서 @autowired 개인 AuthenticationFailureHandler ImooCauthenticationFailureHandler; // 데이터 소스 @autowired Private DataSource DataSource; @autowired private userDetailsService userDetailsService; // org.springframework.security.crypto.password.password.passwordoder @bean public public besponsedencoder passworddencoder () {// bcryptpasswordencoder empactionencoder return new bcryptpasswordencoder (); } /** * Remember my TokenRepository configuration, execute after login successfully* After login successfully, save the token in the database* @Description: Remember my TokenRepository configuration* @param @return JdbcTokenRepositoryImpl * @return PersistentTokenRepository * @throws * @author lihaoyang * @date March 5, 2018*/ @Bean public persistentTokenRepository persistentTokenRepository () {jdbctokenrepositoryimpl jdbctokenrepository = new jdbctokenrepositoryImpl (); jdbctokenrepository.setdatasource (dataSource); // 해당 테이블이 시작시 자동 생성됩니다. create_table_sql 스크립트를 jdbctokenrepositoryimpl에서 직접 실행하여 테이블 JDBCTokenRepository.setCreatetableOnStartup (true)을 생성 할 수 있습니다. jdbctokenrepository를 반환합니다. } // 버전 2 : 구성 가능한 로그인 페이지 @override protected void configure (httpsecurity http)는 예외 {// valter validatecodeFilter validAteCodeFilter = new validAcodeFilter (); // 확인 코드 필터 ValidAcodeFilter.SetAuthenticationFailureHandler (ImooCauthenticationFailureHandler)에서 자신의 오류 처리를 사용합니다. // 구성 검증 코드 필터 URL ValidAcodeFilter.SetSecurityProperties (SecurityProperties); validAteCodeFilter.AfTerProperTiesset (); // 인증, 보안 = 인증 + 인증이 필요한 인터페이스 점프 양식 로그인 구현 //http.httpbasic () // 이것은 기본 팝업 상자 인증 // http // 로그인 필터 전에 확인 코드 필터를로드합니다. configuration.formlogin () .LoginPage ( "/Authentication/require") // 사용자 인증 BrowsersEcurityController 처리 필터링 필터 usernamepasswordauthenticationFilter 기본 로그인 URL은 "/auginProcessingUrl ("/authenticing/compeN ")입니다. .successhandler (imoocauthenticationsuccesshandler) // 사용자 정의 인증 postprocessor.failurehandler (imoocauthenticationfailurehandler) // 로그인 후 처리가 실패한 후 () // 내 관련 구성을 기억하십시오 .rememberme () .tokenrepositority (persistentokenrepositority ()) // 토크 렌즈 포지티브 (persistentokenrepositority) // TokenValiditySeconds (securityProperties.getBrowser (). getRememberMeseconds ()) // Seconds.userDetailsService (userDetailsService) // query user user information.and () // 관련 구성 ()//////////////////////////////////////////////////////////////////////////////////////////////////// login, securityproperties.getBrowser (). getLoginPage () : 사용자 구성 로그인 페이지 .AntMatchers ( "/augentication/require", infocentication/require " // anyRequest.authenticated () // 인증 인증이 필요합니다. }} curity.browser;데이터베이스를 처리하려면 데이터 소스를 주입해야합니다.
spring.datasource.driver-class-name = com.mysql.jdbc.driverspring.datasource.url = jdbc : mysql : //127.0.0.1 : 3306/imooc-demospring.datasource.username = rootspring.datasource.pass root
응용 프로그램을 시작하고 LocalHost : 8080/사용자에 액세스하고 로그인이 필요합니다
성공적으로 로그인 :
데이터베이스 : Peristent_Logins 테이블을 생성하고 데이터 저장
서비스를 중지하고 다시 시작하십시오 ( jdbcTokenRepository.setCreateTableOnStartup(true); ) 사용자 로그인 정보가 세션에 있으므로 서비스를 다시 시작한 후 로그인 페이지로 재부팅해야하지만 나에게 직접 액세스하고 인터페이스 데이터를 얻을 수 있기 때문에 인터페이스 데이터를 얻을 수 있습니다.
요청 헤더 :
지금까지 기본 기억이 완성되었습니다
전체 코드는 github : https://github.com/lhy1234/spring-security에 배치됩니다
요약
위는 편집자가 소개 한 Spring Security Construction REST Service입니다. 나를 기억하십시오. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!