在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响应。