我正在使用swagger 3,我想添加授权与“承载令牌”来调用此API。我咨询了chatGpt,并被指示添加“@Parameter(name =“Authorization”,description =“Bearer token”,required = true,in = ParameterIn.HEADER)”,但它无法正常工作,有人可以指导我吗?
@Operation(
description = "Create post, USER/ADMIN",
responses = {
@ApiResponse(content = @Content(schema = @Schema(implementation = PostResponseDTO.class)), responseCode = "200")})
@ApiResponses(
value = {
@ApiResponse(responseCode = "200", description = "200"),
@ApiResponse(responseCode = "401", description = "401", content = @Content(schema = @Schema(implementation = ErrorDTO.class))),
@ApiResponse(responseCode = "403", description = "403", content = @Content(schema = @Schema(implementation = ErrorDTO.class))),
@ApiResponse(responseCode = "404", description = "404", content = @Content(schema = @Schema(implementation = ErrorDTO.class)))
})
@PostMapping
@PreAuthorize("hasAnyRole('USER','ADMIN')")
@io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(
mediaType = "multipart/form-data",
schema = @Schema(implementation = FormUpload.class)
))
@Parameter(name = "Authorization", description = "Bearer token", required = true, in = ParameterIn.HEADER)
public PostResponseDTO createPost(
@Valid @RequestPart("post") PostRequestDTO postRequestDTO,
@RequestPart(required = false) MultipartFile[] file) throws IOException {
if (!(filesService.notEmpty(file) && filesService.isSingleFile(file) && filesService.isImageFile(file[0]) && filesService.maxSize(file[0], 5))) {
}
return postService.save(postRequestDTO, file);
}
字符串
这是Swagger UI x1c 0d1x
1条答案
按热度按时间hgqdbh6s1#
首先需要在swagger配置中定义安全方案,可以使用注解
@SecurityScheme
来完成字符串
在你设置了安全方案之后,你可以在你的API中为下面的端点定义
@SecurityRequirement
的安全需求。型
确保安全要求与之前设置的安全方案匹配。以下是关于安全需求的github文档的引用。
每个属性使用的名称必须对应于组件对象下的安全方案中声明的安全方案。
您还可以将硬编码字符串更改为已定义的常量变量。
下面是参考link