下面我会给出详细的攻略,分为以下步骤:
- 添加pom依赖
- 配置Remember-me
- 编写HTML页面
- 编写Controller
- 运行测试
下面我会对每个步骤进行详细的讲解:
1. 添加pom依赖
在pom.xml中添加Spring Security和Spring Web的依赖。示例pom.xml文件如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
2. 配置Remember-me
在Spring Security的配置类中添加Remember-me的配置,示例代码如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.and()
.rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(3600)
.rememberMeParameter("remember-me")
.and()
.logout()
.logoutSuccessUrl("/login");
}
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, authority from authorities where username=?")
.passwordEncoder(new BCryptPasswordEncoder());
}
}
注意这里需要注入一个DataSource,这里的实现使用的是Spring Boot默认自带的H2数据库。使用JdbcTokenRepositoryImpl来保存Remember-me的持久化信息。
3. 编写HTML页面
在登录页面中添加Remember-me的勾选框,示例代码如下:
<form method="post" th:action="@{/login}" id="login-form">
<div th:if="${param.error}" class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
用户名或密码不正确
</div>
<div th:if="${param.logout}" class="alert alert-info alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
已成功退出登录
</div>
<h2 class="form-signin-heading">登录</h2>
<label for="inputUsername" class="sr-only">用户名</label>
<input type="text" id="inputUsername" name="username" class="form-control" placeholder="用户名" required autofocus>
<label for="inputPassword" class="sr-only">密码</label>
<input type="password" id="inputPassword" name="password" class="form-control" placeholder="密码" required>
<div class="checkbox">
<label>
<input type="checkbox" name="remember-me" value="true"> 自动登录
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
</form>
4. 编写Controller
编写SimpleController,其中包含/login和/home两个方法。
@Controller
public class SimpleController {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleController.class);
@RequestMapping("/login")
public String login() {
return "login";
}
@RequestMapping("/home")
public String home() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
LOGGER.info("当前登录用户名:{}", auth.getName());
return "home";
}
}
5. 运行测试
启动Spring Boot应用,在浏览器中访问http://localhost:8080/login,输入用户名和密码,勾选记住我,点击登录按钮。登录成功后跳转到http://localhost:8080/home,并输出当前登录的用户名。
再次打开浏览器,访问http://localhost:8080/home,会自动登录。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring Security学习之rememberMe自动登录的实现 - Python技术站