Spring Security整合spring boot
时间: 2023-07-13 20:39:03 浏览: 65
要在 Spring Boot 中使用 Spring Security,需要进行以下步骤:
1. 添加 Spring Security 依赖。
在 `pom.xml` 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 配置 Spring Security。
在 Spring Boot 中,可以通过 `WebSecurityConfigurerAdapter` 来配置 Spring Security。创建一个类继承 `WebSecurityConfigurerAdapter`,并重写其中的方法来配置 Spring Security。
例如:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin123"))
.roles("ADMIN")
.and()
.withUser("user")
.password(passwordEncoder().encode("user123"))
.roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
上述代码中,`configure(HttpSecurity http)` 方法用于配置 URL 的访问权限,`configure(AuthenticationManagerBuilder auth)` 方法用于配置用户的认证信息。在上述示例中,配置了两个角色 ADMIN 和 USER,分别具有不同的访问权限。
3. 使用 Spring Security。
在 Spring Security 配置完成后,可以在 Spring Boot 项目的其他地方使用 Spring Security。例如,在控制器中使用注解 `@PreAuthorize` 来控制方法的访问权限。
例如:
```java
@RestController
@RequestMapping("/admin")
public class AdminController {
@GetMapping("/hello")
@PreAuthorize("hasRole('ADMIN')")
public String helloAdmin() {
return "Hello, Admin!";
}
}
```
上述代码中,`@PreAuthorize("hasRole('ADMIN')")` 注解用于控制该方法只能被具有 ADMIN 角色的用户访问。
以上就是在 Spring Boot 中整合 Spring Security 的基本步骤。