gpt4 book ai didi

java - 具有默认安全性的 Spring Security 为 PUT 提供 401,为 GET 提供 200

转载 作者:行者123 更新时间:2023-12-01 17:43:17 26 4
gpt4 key购买 nike

我开发了一个具有基本安全性的 Spring Boot 应用程序。我有两个具有相同路径和不同 http 方法的端点。当我使用默认密码/使用 application.yml 中给出的密码包含基本安全性时,GET api/products/{id} 经过身份验证,而 PUT api/products/{id} 给出 401 未经授权。

我的代码有什么问题?我是否错过了任何了解 Spring 安全性的内容?我可能错过的有关 Spring Security 的任何链接都会有帮助吗?

我的代码片段如下,

我的 Controller

@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'
}

提前致谢

更新了 postman 屏幕截图: enter image description here enter image description here

最佳答案

这可能是 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();
}
}

关于java - 具有默认安全性的 Spring Security 为 PUT 提供 401,为 GET 提供 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com