springboot保持登录状态
时间: 2023-08-28 16:06:07 浏览: 30
在 Spring Boot 中保持登录状态可以使用 Spring Security 框架来实现。下面是一个简单的示例:
1. 添加依赖
在 pom.xml 中添加以下依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
```
2. 配置 Spring Security
在 Spring Boot 应用程序中配置 Spring Security,可以通过创建一个类并扩展 WebSecurityConfigurerAdapter 类来实现。
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
```
在上面的代码中,我们配置了一个基本的 Spring Security 设置,其中包括:
- 所有请求都需要经过身份验证才能访问
- 用于登录的自定义登录页面
- 支持用户注销的功能
3. 实现 UserDetailsService
在上面的代码中,我们需要实现一个 UserDetailsService 接口来获取用户详细信息。以下是一个示例实现:
```java
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthority(user));
}
private Set<SimpleGrantedAuthority> getAuthority(User user) {
Set<SimpleGrantedAuthority> authorities = new HashSet<>();
user.getRoles().forEach(role -> {
authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
});
return authorities;
}
}
```
4. 编写登录页面
在 Spring Security 配置中我们指定了自定义登录页面,因此需要编写一个登录页面。以下是一个简单的示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="POST" action="/login">
<label for="username">Username</label>
<input type="text" id="username" name="username" required autofocus><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
```
5. 保持登录状态
在登录成功后,Spring Security 会自动将用户信息存储在 HttpSession 对象中。因此,我们可以通过以下方式在应用程序中保持登录状态:
```java
@GetMapping("/profile")
public String showProfilePage(Model model, Principal principal) {
String username = principal.getName();
User user = userRepository.findByUsername(username);
model.addAttribute("user", user);
return "profile";
}
```
上面的代码中,我们注入了一个 Principal 对象,它可以用于获取当前已经通过身份验证的用户的信息。在该示例中,我们使用该 Principal 对象获取了当前用户的用户名,并从 UserRepository 中获取了完整的用户信息,然后将其添加到模型中传递给视图。