Java 如何在spring中禁用默认的GET请求,因为它公开了所有数据?
我有一个具有以下映射的Spring控制器Java 如何在spring中禁用默认的GET请求,因为它公开了所有数据?,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,我有一个具有以下映射的Spring控制器 @RestController 公共类用户控制器{ 公共用户服务; 公共用户控制器(用户服务){ 服务=服务; } @后期映射(“/users/create”) ResponseEntity创建(@RequestBody用户){ 返回新的ResponseEntity(this.service.create(user),HttpStatus.CREATED); } @GetMapping(“/users/{id}”) ResponseEntity getB
@RestController
公共类用户控制器{
公共用户服务;
公共用户控制器(用户服务){
服务=服务;
}
@后期映射(“/users/create”)
ResponseEntity创建(@RequestBody用户){
返回新的ResponseEntity(this.service.create(user),HttpStatus.CREATED);
}
@GetMapping(“/users/{id}”)
ResponseEntity getById(@PathVariable Long id){
返回ResponseEntity.ok(this.service.findById(id));
}
@GetMapping(“/users/all”)
列表getAll(){
返回此.service.findAll();
}
@PutMapping(“/users/{id}”)
用户updateUser(@RequestBody User newUser,@PathVariable Long id){
返回this.service.updateUser(newUser,id);
}
@DeleteMapping(“/users/{id}”)
void deleteUser(@PathVariable Long id){
this.service.deleteById(id);
}
}
当我向http://localhost:8080/users/all
我按预期获得了所有用户的列表。但是我注意到,如果我发送一个GET请求到http://localhost:8080/users
它返回一个包含所有数据的列表,如下所示
{
"_embedded": {
"users": [
{
"admin": false,
"name": "Name",
"_links": {
"self": {
"href": "http://localhost:8080/users/1"
},
"user": {
"href": "http://localhost:8080/users/1"
},
"tickets": {
"href": "http://localhost:8080/users/1/tickets"
}
}
},
{
"admin": false,
"name": "Example",
"_links": {
"self": {
"href": "http://localhost:8080/users/2"
},
"user": {
"href": "http://localhost:8080/users/2"
},
"tickets": {
"href": "http://localhost:8080/users/2/tickets"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/users"
},
"profile": {
"href": "http://localhost:8080/profile/users"
}
},
"page": {
"size": 20,
"totalElements": 4,
"totalPages": 1,
"number": 0
}
}
为什么spring能够返回此数据,即使它没有显式映射,我如何禁用它。这只是为了个人培训,所以安全性并不重要,但我想知道如何避免这种情况,因为如果这是真的,我可能会意外地暴露所有数据
如有任何建议,将不胜感激,谢谢
更新:
有人建议GET(/users/{id})映射使用空值,因此我将其注释掉,并尝试再次调用它。提供一个号码返回405,因为该服务已不存在,但我尝试了http://localhost:8080/users/ 同样,它仍然返回上面显示的所有数据,看起来您在Spring数据Rest中使用的是HATEOAS格式
您可以通过设置参数来禁用它:spring.data.rest.defaultMediaType=application/json看起来您在spring数据rest中使用的是HATEOAS格式
您可以通过设置参数来禁用它:spring.data.rest.defaultMediaType=application/json我已经找到了解决方案,添加了:
@SpringBootApplication(exclude = RepositoryRestMvcAutoConfiguration.class)
到main方法将禁用HATEOAS函数
我从这篇文章中找到了解决方案:
我设法找到了解决方案,添加了:
@SpringBootApplication(exclude = RepositoryRestMvcAutoConfiguration.class)
到main方法将禁用HATEOAS函数
我从这篇文章中找到了解决方案:
默认情况下,需要使用
@PathVariable
注释的托马斯方法参数。如果它是可选的,则需要使用required=false
来猜测(不是真的)您将spring引导启动器数据rest
作为依赖项。如果是,请删除它。@Thomas方法参数默认情况下需要使用@PathVariable
注释。如果它是可选的,则需要使用required=false
来猜测(不是真的)您将spring引导启动器数据rest
作为依赖项。如果是这样,请删除它。我刚刚尝试将其添加到属性中,它仍然返回所有数据,但格式略有不同。我刚刚尝试将其添加到属性中,它仍然返回所有数据,但格式略有不同。如果您不想使用spring data rest
,请不要包含依赖项。如果您不想使用spring数据rest
只是不包括依赖项。