Spring Security 如何添加Header - Authorization for swagger 3,spring Boot

izkcnapc  于 2023-08-05  发布在  Spring
关注(0)|答案(1)|浏览(108)

我正在使用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

hgqdbh6s

hgqdbh6s1#

首先需要在swagger配置中定义安全方案,可以使用注解@SecurityScheme来完成

@SecurityScheme(
        name = "Authorization",
        type = SecuritySchemeType.HTTP,
        bearerFormat = "JWT",
        scheme = "bearer"
)
public class SwaggerConfiguration {...}

字符串
在你设置了安全方案之后,你可以在你的API中为下面的端点定义@SecurityRequirement的安全需求。

@SecurityRequirement(name = "Authorization")
public class PostController {...}


确保安全要求与之前设置的安全方案匹配。以下是关于安全需求的github文档的引用。
每个属性使用的名称必须对应于组件对象下的安全方案中声明的安全方案。
您还可以将硬编码字符串更改为已定义的常量变量。
下面是参考link

相关问题