溫馨提示×

springboot怎么限制接口訪問

小億
458
2023-08-14 10:51:05
欄目: 編程語言

在Spring Boot中,可以使用Spring Security來限制接口的訪問。Spring Security是一個基于Spring框架的安全性解決方案,可以幫助我們實現認證和授權的功能。

首先,需要在pom.xml文件中添加Spring Security的依賴:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

然后,在應用的配置類中,可以使用@EnableWebSecurity注解來啟用Spring Security:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").authenticated() // 需要認證才能訪問的接口
.anyRequest().permitAll() // 其他接口允許匿名訪問
.and()
.formLogin()
.and()
.httpBasic();
}
}

在上述配置中,.antMatchers("/api/**").authenticated()表示需要認證才能訪問以/api/開頭的所有接口,.anyRequest().permitAll()表示其他接口允許匿名訪問。

此外,還可以通過@PreAuthorize注解來對接口進行更細粒度的權限控制。例如,在Controller的方法上添加@PreAuthorize注解:

@RestController
public class MyController {
@GetMapping("/api/hello")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String hello() {
return "Hello, world!";
}
}

上述例子中,只有具有ROLE_ADMIN角色的用戶才能訪問/api/hello接口。

通過以上的配置,就可以限制接口的訪問了。當用戶沒有認證或者沒有權限時,Spring Security會自動返回401 Unauthorized或403 Forbidden的HTTP響應。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女