我建立了一个网络服务器,我试图用密码保护它。我正在尝试使用 spring boot 设置基本身份验证。到目前为止,这是我的配置文件:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/v1/occupancy/*")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
这按预期工作并保护了我的 GET 端点之一,允许我进行身份验证。
但是,对于 POST 端点,这不起作用。端点如下所示:
@RequestMapping(path = "/v1/admin/repository")
public class RepositoryOptionsController {
private final EstablishmentOptionsRepositoryService establishmentOptionsRepositoryService;
private final SubAreaOptionsRepositoryService subAreaOptionsRepositoryService;
@PostMapping("/establishment/options")
public ResponseEntity<String> postEstablishmentOption(@RequestBody OptionsRequestDto body) {
当我这样做
curl -X POST "http://localhost:8080/v1/admin/repository/establishment/options" -u root -v -d "{...}"
我明白了
Enter host password for user 'root':
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
* Server auth using Basic with user 'root'
> POST /v1/admin/repository/establishment/options HTTP/1.1
> Host: localhost:8080
> Authorization: Basic cm9vdDpyb290
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Length: 271
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 271 out of 271 bytes
< HTTP/1.1 401
< Set-Cookie: JSESSIONID=6E1CBD875597C83E6DEB794986050631; Path=/; HttpOnly
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
* Authentication problem. Ignoring this.
< WWW-Authenticate: Basic realm="Realm"
< Content-Length: 0
< Date: Sun, 27 Sep 2020 15:29:13 GMT
<
* Connection #0 to host localhost left intact
* Closing connection 0
相同的用户/通行证组合在 GET 上没有问题。做什么?
最佳答案
原因是 httpBasic
和 formLogin
默认开启了 CSRF 防御。因为您的 POST
不包含 CSRF token ,所以 Spring Security 拒绝它。
通过更改配置以允许 /error
端点,您可以更好地了解这一点:
http
.authorizeRequests()
.antMatchers("/", "/v1/occupancy/**", "/error").permitAll()
// ...
然后,当您提交 POST
时,您会看到 403,这与 CSRF token 拒绝有关。
如果您的 REST API 不是面向前端的,那么您可以关闭 CSRF。一种方法是禁用适当的端点:
http
.authorizeRequests()
// ...
.and()
.csrf()
.ignoringAntMatchers("/v1/admin/repository/establishment/options")
// ...
如果它是前置的,那么合适的做法是prepare your front-end to hand the CSRF token back to the request .
关于spring-boot - 基本身份验证不适用于 POST 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64090192/