spring boot security权限分配怎么写
时间: 2023-10-28 12:07:00 浏览: 34
在Spring Boot中,可以使用Spring Security来实现权限控制。下面是一个简单的示例:
1. 添加依赖
在`pom.xml`文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 配置安全设置
在`application.properties`文件中添加以下配置:
```
# 禁用CSRF保护
spring.security.csrf.enabled=false
# 配置用户及其角色
spring.security.user.name=user
spring.security.user.password=password
spring.security.user.roles=USER
# 配置其他角色
security.roles.admin=ROLE_ADMIN
security.roles.user=ROLE_USER
```
3. 定义访问控制规则
在`WebSecurityConfigurerAdapter`类中定义访问控制规则,如下所示:
```
@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()
.logout();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER")
.and()
.withUser("admin")
.password("{noop}password")
.roles("ADMIN");
}
}
```
在上面的配置中,我们定义了两个角色:`ADMIN`和`USER`,并分别为它们指定了访问控制规则。具体来说,访问`/admin/**`的请求需要`ADMIN`角色,访问`/user/**`的请求需要`USER`角色,其他请求需要身份验证。
4. 使用注解控制访问
在Controller层中可以使用注解来控制访问,示例代码如下:
```
@RestController
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {
@GetMapping("/hello")
public String hello() {
return "Hello, admin!";
}
}
@RestController
@RequestMapping("/user")
@PreAuthorize("hasRole('USER')")
public class UserController {
@GetMapping("/hello")
public String hello() {
return "Hello, user!";
}
}
```
在上面的代码中,我们使用`@PreAuthorize`注解来控制访问,指定了需要`ADMIN`或`USER`角色才能访问。