保护一个Spring Boot REST API的常见方法是使用Spring Security。下面是一个使用Spring Security保护REST API的示例:
在pom.xml文件中添加以下依赖:
org.springframework.boot
spring-boot-starter-security
创建一个配置类(如SecurityConfig.java),并使用@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()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("{noop}password").roles("ADMIN");
}
}
上述配置将所有以/api/
开头的URL都要求用户进行身份验证。同时,只有一个名为"admin"的用户(密码为"password")被授予了"ADMIN"角色。
在需要进行身份验证的Controller方法上添加@PreAuthorize
注解。例如:
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/data")
@PreAuthorize("hasRole('ADMIN')")
public String getData() {
return "Protected data";
}
}
上述示例中,只有拥有"ADMIN"角色的用户才能访问/api/data
接口。
这样,我们就保护了Spring Boot REST API,并使用Spring Security进行了身份验证和授权。