springBoot security拦截一个url,其他直接通过
时间: 2023-11-16 21:06:19 浏览: 29
在 Spring Boot Security 中拦截一个 URL,可以使用以下代码:
1. 创建一个 Security 配置类,并使用 @EnableWebSecurity 注解开启 Web 安全配置。
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/restricted/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin();
}
}
```
2. 在 configure 方法中,使用 HttpSecurity 对象进行配置,其中:
- `authorizeRequests()` 方法用于配置请求授权规则;
- `antMatchers("/restricted/**").authenticated()` 方法用于匹配需要身份验证的 URL;
- `anyRequest().permitAll()` 方法用于授权其他所有 URL;
- `formLogin()` 方法用于配置表单登录。
3. 在 antMatchers 方法中,可以使用通配符 "*" 匹配任何字符,使用 "**" 匹配任何路径。
例如,如果想要拦截 /api/v1/** 路径下的所有请求,并要求用户进行身份验证,可以使用以下代码:
```
http.authorizeRequests()
.antMatchers("/api/v1/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin();
```
这样,/api/v1/ 下的所有请求都会被拦截并要求用户进行身份验证,其他请求则直接通过。