Как документировать аутентификацию на основе форм, реализованную spring security с помощью spring-doc-openapi?

#forms-authentication #openapi #springdoc

Вопрос:

Я внедряю аутентификацию для своего api REST, и у меня проблемы с документами. Я написал аутентификацию с помощью аутентификации на основе форм безопасности spring. При успехе это дает мне возможность поддерживать аутентификацию seesion. Я не нашел способа сделать spring-doc-openapi, чтобы найти контроллер безопасности spring по умолчанию для операций входа/выхода. Единственный способ, который я нашел — сделать из них подделки вот так:

 @RestController
@RequestMapping(value = "/")
public class FakeSecurityController {

    /**
     * Implemented by Spring Security
     */
    @Operation(summary = "Login with the given credentials.")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200",
                    description = "Login processing url",
                    content = @Content(schema = @Schema(implementation = AuthDTO.class)),
                    headers = @Header(name = "SESSION", description = "Cookie", required = true, schema = @Schema(implementation = String.class)))
    })
    @PostMapping(value = "/login", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<AuthDTO> login(@RequestParam("username") String username,
                                         @RequestParam("password") String password) {
        throw new IllegalStateException("Add Spring Security to handle authentication");
    }

    /**
     * Implemented by Spring Security
     */
    @Operation(summary = "Logout the current user.")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Logout processing url")
    })
    @PostMapping(value = "/logout")
    @SecurityRequirements
    public void logout() {
        throw new IllegalStateException("Add Spring Security to handle authentication");
    }
}
 

Что я должен сделать, чтобы документ spring-doc-openapi документировал эти конечные точки сам по себе?

Ответ №1:

Если в вашем проекте используется spring-security, вам следует добавить следующую зависимость в сочетании с зависимостью springdoc-openapi-ui: эта зависимость помогает игнорировать @AuthenticationPrincipal и предоставляет конечную точку spring-security /login из коробки:

 <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-security</artifactId>
      <version>${springdoc.version}</version>
</dependency>