spring doc swagger ui 에 bearer token 기반의 authentication 을 추가해보았다
Summary
spring doc swagger ui 에서 jwt authentication header 를 추가하는 방법
SwaggerConfig 에 @SecurityScheme 추가
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
@SecurityScheme(name = "Bearer Authentication", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer")
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI().components(new Components()).info(apiInfo());
}
private Info apiInfo() {
return new Info().title("web novel service 테스트를 위한 Swagger UI")
.description("swagger-ui by spring restdocs open-api")
.version("1.0.0");
}
}
@SecurityScheme(name = “Bearer Authentication”, type = SecuritySchemeType.HTTP, bearerFormat = “JWT”, scheme = “bearer”)
bearerFormat 을 JWT 로, scheme 은 bearer 로 지정
SecurityScheme 을 적용할 controller method 에 annotation 추가
1
2
3
4
5
6
7
8
9
10
11
12
@RestController
@RequestMapping("/api/v1")
public class UserController {
@Operation(summary = "user info", description = "get information of current user")
@SecurityRequirement(name = "Bearer Authentication")
@GetMapping("/user/me")
@PreAuthorize("hasRole('USER')")
public User getCurrentUser(@CurrentUser UserPrincipal userPrincipal) {
return userRepository.findById(userPrincipal.getId())
.orElseThrow(() -> new ResourceNotFoundException("User", "id", userPrincipal.getId()));
}
}