写一个 springboot整合spring security 6的项目
时间: 2023-07-07 15:45:55 浏览: 60
好的,以下是一个简单的 Spring Boot 整合 Spring Security 6 的项目示例:
首先,需要在 pom.xml 文件中添加相关依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>6.0.1</version>
<scope>test</scope>
</dependency>
```
然后,在 Spring Boot 的 Application 类上添加 `@EnableWebSecurity` 注解:
```java
@SpringBootApplication
@EnableWebSecurity
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
接下来,创建一个类继承 `WebSecurityConfigurerAdapter` 并重写 `configure(HttpSecurity http)` 方法来配置安全规则:
```java
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
}
```
在上面的代码中,我们配置了 `/login` 路径为公开访问,其他路径需要进行身份验证。同时,我们设置了一个基于内存的用户存储并指定了一个用户名和密码。
最后,创建一个简单的登录页面:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="post" action="/login">
<label for="username">Username:</label>
<input type="text" id="username" name="username" /><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" /><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
```
以上就是一个简单的 Spring Boot 整合 Spring Security 6 的项目示例。