簡體   English   中英

具有默認安全性的 Spring Security 為 PUT 提供 401,為 GET 提供 200

[英]Spring Security with default security gives 401 for PUT and 200 for GET

我開發了一個具有基本安全性的 Spring Boot 應用程序。 我有兩個具有相同路徑和不同 http 方法的端點。 當我使用 application.yml 中給出的默認密碼/密碼包含基本安全性時,GET api/products/{id} 已通過身份驗證,而 PUT api/products/{id} 提供 401 未經授權。

我的代碼有什么問題? 我錯過了了解 Spring 安全性的任何內容嗎? 我可能錯過的春季安全性鏈接會有幫助嗎?

我的代碼片段如下,

我的控制器

@RestController
@RequestMapping(value = "api")
public class ProductController {

    @RequestMapping(value = "/products/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> getById(@PathVariable(value = "id") Integer id) {
           //Implementation

    }

    @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity updateById(@PathVariable(value = "id") Integer id,
                                                                   @RequestBody UpdateProductRequest updateProductRequest) {
        //Implementation
    }
}

應用程序.yml

spring:
  security:
    user:
      name: admin
      password: admin

build.gradle 依賴項

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-openfeign', version: '2.2.0.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'

    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    implementation 'junit:junit:4.12'
}

提前致謝

使用郵遞員截圖更新: 在此處輸入圖片說明 在此處輸入圖片說明

您的問題是跨站點請求偽造 (CSRF)。 請參閱問題及其答案。

有關CSRF更多信息,請參閱站點。

這可能是 Csrf 配置問題。

您必須覆蓋WebSecurityConfigurerAdapter

嘗試這個..

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.cors();
    http.authorizeRequests().anyRequest().fullyAuthenticated();
    http.httpBasic();
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM