标题:Spring Security安全框架之记住我功能详解
什么是记住我功能
记住我功能是指,在用户登录成功后,用户的身份认证信息会保持在客户端的cookie中,以便用户下次访问同一站点时不需要再次登录。
Spring Security中如何实现记住我功能
要在Spring Security中实现记住我功能,需要进行以下几个步骤:
1.在spring security的配置文件中配置rememberMe()方法
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.rememberMe()
.key("uniqueAndSecret")
.rememberMeParameter("remember-me")
.rememberMeCookieName("my-remember-me")
.tokenValiditySeconds(24 * 60 * 60)
.dataSource(dataSource);
}
}
- 在登录页面中增加remember-me元素
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required />
<br />
<label for="password">Password:</label>
<input type="password" id="password" name="password" required />
<br />
<input type="checkbox" id="remember-me" name="remember-me"
value="true" />
<label for="remember-me">Remember me on this computer</label>
<br />
<input type="submit" value="Login" />
</form>
增加remember-me元素后,用户勾选remember me选项时,会在cookie中记录用户的身份信息。
记住我功能示例
示例一:使用内存存储用户信息
配置内存用户信息
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth
.inMemoryAuthentication()
.withUser("user").password(encoder.encode("password")).roles("USER").and()
.withUser("admin").password(encoder.encode("password")).roles("ADMIN");
}
}
配置记住我
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.rememberMe()
.key("uniqueAndSecret")
.rememberMeParameter("remember-me")
.rememberMeCookieName("my-remember-me")
.tokenValiditySeconds(24 * 60 * 60)
.dataSource(dataSource);
}
}
测试
运行程序,在浏览器输入http://localhost:8080/admin,应该会跳转到登录页面。输入正确的用户名和密码,并勾选remember-me选项,登录成功后,点击退出登录,再次访问http://localhost:8080/admin,会发现不需要再次登录即可访问该页面。
示例二:使用JDBC存储用户信息
创建用户表和remember-me持久化表
CREATE TABLE users
(
username VARCHAR(50) NOT NULL PRIMARY KEY,
password VARCHAR(100) NOT NULL,
enabled TINYINT(1) NOT NULL,
authority VARCHAR(50) NOT NULL);
CREATE TABLE persistent_logins
(
username VARCHAR(64) NOT NULL,
series VARCHAR(64) NOT NULL PRIMARY KEY,
token VARCHAR(64) NOT NULL,
last_used TIMESTAMP NOT NULL
);
配置JDBC用户信息
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select username,password,enabled "
+ "from users "
+ "where username = ?")
.authoritiesByUsernameQuery("select username,authority "
+ "from authorities "
+ "where username = ?")
.passwordEncoder(encoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.rememberMe()
.key("uniqueAndSecret")
.rememberMeParameter("remember-me")
.rememberMeCookieName("my-remember-me")
.tokenValiditySeconds(24 * 60 * 60)
.dataSource(dataSource);
}
}
测试
同样在运行程序,访问http://localhost:8080/admin,输入正确的用户名和密码,并勾选remember-me选项,登录成功后,点击退出登录,再次访问http://localhost:8080/admin,会发现不需要再次登录即可访问该页面。
小结
Spring Security提供了方便的记住我功能,让用户在下一次访问同一站点时不需要再次登录。可以通过内存存储用户信息和JDBC存储用户信息两种方式配置记住我功能。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring Security安全框架之记住我功能 - Python技术站