springboot 接口认证
时间: 2023-11-18 15:52:00 浏览: 53
在 Spring Boot 中可以使用 Spring Security 进行接口认证。以下是简单的步骤:
1. 添加 Spring Security 依赖。
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 创建一个类继承 WebSecurityConfigurerAdapter,并覆盖 configure 方法。
```
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and().httpBasic();
}
}
```
上述代码将所有以 /api 开头的请求都需要认证,其他请求不需要认证。
3. 在 application.properties 或 application.yml 中配置用户名和密码。
```
spring.security.user.name=user
spring.security.user.password=password
```
现在你的接口将需要用户名和密码才能访问。