Search code examples
spring-bootspring-securityswagger-2.0swagger-3.0

How to add Header - Authorization for swagger 3, spring boot


I am using swagger 3, I want to add Authorization with "Bearer token" to call this api. I consulted with chatGpt and was instructed to add "@Parameter(name = "Authorization", description = "Bearer token", required = true, in = ParameterIn.HEADER)" but it doesn't work properly, can someone guide me?

@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);
}

This is Swagger UI enter image description here


Solution

  • First thing you need to define the security scheme in your swagger configuration you can do it with the annotation @SecurityScheme

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

    After you set the security scheme then in your api you can define the security requirement for the following endpoint with @SecurityRequirement.

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

    Make sure the security requirement match with the security scheme you set before. Here is the quote from the following github documentation about the security requirement.

    The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object.

    You can also change the hardcoded string to your defined constant variables.

    Here is the reference link