首页 > 解决方案 > 具有默认安全性的 Spring Security 为 PUT 提供 401,为 GET 提供 200

问题描述

我开发了一个具有基本安全性的 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'
}

提前致谢

更新了邮递员截图: 在此处输入图像描述在此处输入图像描述

标签: javaspringspring-bootspring-security

解决方案


您的问题是跨站请求伪造(CSRF)。请参阅问题及其答案。

有关更多信息,CSRF请参见网站。


推荐阅读