Spring Security 5.2.2 + Spring Boot 2.2 + Oauth Autoconuration : 允许一些尿素,只保证少数尿素的安全。403错误

问题描述 投票:0回答:1

我有一个授权服务器和资源服务器,我已经自动配置了OAuth的默认实现。

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          jwk-set-uri:<auth server configuration url here>

Maven依赖性

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>
                spring-boot-starter-oauth2-resource-server
            </artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

目前,我所有的urls都得到了保障。

@PostMapping(path = "/secure/test", consumes = "application/json", produces = "application/json")   
    public @ResponseBody String testService(@RequestBody String name ,@RequestHeader Map<String, String>headers) {
headers.forEach((K,V)->printHeaders(K,V));
}

我希望我下面的uri能够被所有人访问。

@PostMapping(path = "/test", consumes = "application/json", produces = "application/json")  
    public @ResponseBody String testAuthService(@RequestBody String name ,@RequestHeader Map<String, String>headers) {
headers.forEach((K,V)->printHeaders(K,V));
}

我试着覆盖下面的内容,但在没有bearer token的情况下,得到403错误信息。

@Configuration
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) {
        try {
            http
                .authorizeRequests(authorize -> authorize
                    .mvcMatchers("/api/secure/**").authenticated()
                    .anyRequest().permitAll()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

错误响应

{
    "timestamp": "2020-05-07T14:28:22.729+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/api/test"
}

如何使用Spring Security 5.2.2 + Spring Boot 2.2 + Oauth Autoconfiguration只允许某些URL进行认证?

spring-security spring-security-oauth2
1个回答
0
投票

如果你得到一个 403 当你 POST 你可能忘了提供一个 crsrf-token

在Java配置中,CSRF保护是默认启用的,但你可以禁用它。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
      .csrf().disable()                 // <--- disable CSRF 
      .authorizeRequests(...
      ....

或者在您的表单中提供一个标记。

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

如果您使用的是JSON,您不能将CSRF标记作为参数提交,而是在header中提交标记。

<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>

JS来附加头。

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
});

© www.soinside.com 2019 - 2024. All rights reserved.