给一个springboot security demo
时间: 2023-06-01 18:01:35 浏览: 147
这里提供一个简单的Spring Boot Security Demo,实现了用户登录和注销功能。
1. 创建Spring Boot项目
使用Spring Initializr创建一个新的Spring Boot项目,选择Web和Security依赖。
2. 配置Security
在Spring Boot项目中配置Security,使用@EnableWebSecurity注解启用Security。
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
这里配置了用户访问授权和登录、注销的处理。登录使用了自定义的登录页面,登录成功后跳转到/home页面。
3. 定义User类和UserDetailsService
定义User类,表示用户信息。
```
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements UserDetails {
private String username;
private String password;
private List<GrantedAuthority> authorities;
private boolean enabled;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
}
```
定义UserDetailsService,返回User对象。
```
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 从数据库查询用户信息
User user = new User();
user.setUsername(username);
user.setPassword(passwordEncoder.encode("123456"));
user.setAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")));
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setAccountNonLocked(true);
user.setCredentialsNonExpired(true);
return user;
}
}
```
这里只是简单地将密码加密后返回User对象,实际应用中需要从数据库或其他存储中获取用户信息。
4. 定义Controller
定义登录、注销和首页的Controller。
```
@Controller
public class HomeController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/home")
public String home() {
return "home";
}
@GetMapping("/logout")
public String logout() {
return "logout";
}
}
```
5. 编写视图
编写登录、注销和首页的视图。
login.html
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="/login" method="post">
<div>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<button type="submit">Login</button>
</form>
</body>
</html>
```
home.html
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Welcome to Home Page</h1>
<a href="/logout">Logout</a>
</body>
</html>
```
logout.html
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Logout</title>
</head>
<body>
<h1>Logout Successfully</h1>
<a href="/login">Login Again</a>
</body>
</html>
```
6. 运行项目
运行Spring Boot项目,访问http://localhost:8080/login,输入用户名和密码(这里用户名和密码都是admin),即可登录到首页。在首页点击Logout链接可以注销登录。
阅读全文