创建数据库表
CREATE TABLE `persistent_logins` (
`username` varchar(64) NOT NULL,
`series` varchar(64) NOT NULL,
`token` varchar(64) NOT NULL,
`last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP,
PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
??也可以不手动创建,JdbcTokenRepositoryImpl中有定义的sql,能自动创建
public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements
PersistentTokenRepository {
public static final String CREATE_TABLE_SQL = "create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, "
+ "token varchar(64) not null, last_used timestamp not null)";
public static final String DEF_TOKEN_BY_SERIES_SQL = "select username,series,token,last_used from persistent_logins where series = ?";
public static final String DEF_INSERT_TOKEN_SQL = "insert into persistent_logins (username, series, token, last_used) values(?,?,?,?)";
public static final String DEF_UPDATE_TOKEN_SQL = "update persistent_logins set token = ?, last_used = ? where series = ?";
public static final String DEF_REMOVE_USER_TOKENS_SQL = "delete from persistent_logins where username = ?";
WebSecurityConfig注入数据源、配置操作数据库对象
@Autowired
private DataSource dataSource;
@Autowired
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
return jdbcTokenRepository;
}
配置自动登录
@Override
protected void configure(HttpSecurity http) throws Exception {
http.logout().logoutUrl("/logout")
.logoutSuccessUrl("/test/hello").permitAll();
http
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/user/login")
.defaultSuccessUrl("/success.html").permitAll()
.and().authorizeRequests()
.antMatchers("/","/test/hello","/test/erro").permitAll()
.antMatchers("/test/index").hasAnyRole("sale","role")
.anyRequest().authenticated()
.and().rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(20)
.userDetailsService(userDetailsService)
.and().csrf().disable();
}
登录界面增加记住我选框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/api/auth/user/login" method="post">
<input type="text" name="username" placeholder="输入用户名"/>
<input type="text" name="password" placeholder="输入密码"/>
<input type="checkbox" name="remember-me"/>自动登录
<br>
<button>登录</button>
</form>
</body>
</html>
??此处:name 属性值必须位 remember-me.不能改为其他值
访问控制
@GetMapping("update")
@PostAuthorize("hasAnyAuthority('admins')")
public String update(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = dateFormat.format(new Date());
Date date = new Date(System.currentTimeMillis()+30*1000);
String e = dateFormat.format(date);
return "自动登录开始时间->"+s+" 过期时间->"+e;
}
测试
??1、查看Cookie变化
??2、数据库变化
??3、有效时长准确性,维护的时间和北京时间相差8个小时,是时区影响导致,我们只看分秒
??4、在有效期内关掉游览器是否能自动登录,过期后是否需要再次登录
??动态图片太大了,上传不上来可以跳到有道笔记上去看:图片
??以上都已实现;
|