1つは、SpringSecurityの考えです
赤は、初めてログインするときにトークンを自動的に保存するプロセスを表します
青は、ブラウザを閉じた後の2回目の訪問のトークン検索とデータ比較のプロセスを表します
次に、自動ログインを実現します
1.構成クラスでPersistentTokenRepositoryを構成して、トークンデータの処理方法を決定します
//1、配置数据源
@Autowired
private DataSource dataSource;
//配置PersistentTokenRepository,该类用于配置token数据的处理方式
//1、JdbcTokenRepositoryImpl 将token数据持久化(通过数据保存token)
//2、InMemoryTokenRepositoryImpl 将token数据存在内存中
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
//配置数据源
jdbcTokenRepository.setDataSource(dataSource);
//自动生成存储token的表
//jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
2. WebSecurityConfigurerAdapter configure(HttpSecurity httpSecurity)の実装方法を構成します
public void configure(HttpSecurity httpSecurity) throws Exception {
// httpSecurity.exceptionHandling().accessDeniedPage("/403"); /* 配置没有权限访问条状自定义页面 */
//用户登录
....
//权限设置
....
//token配置
.and().rememberMe().tokenRepository(persistentTokenRepository()) /* 2、设置PersistentTokenRepository */
.tokenValiditySeconds(60) /* 设置有效时长,单位秒 */
.userDetailsService(userDetailsService)
.and().csrf().disable(); /* 关闭csrf防护 */
//用户注销
....
}
3フロントエンドページのチェックボックスを設定し、その名前属性をremember-meに設定します
<body>
<h1>my login page</h1>
<!-- action要与配置中的登录访问路径一致 -->
<form action="/user/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<!-- 设置checkbox 的name为 remember-me -->
<input type="checkbox" name="remember-me">自动登录<br>
<input type="submit" value="login">
</form>
</body>
4.操作効果