Spring/ETC

swagger 에 jwt token 추가하기

YoonJong 2022. 12. 21. 16:19
728x90

아래의 문서를 참고하면 더욱 쉽게 이해할 수 있다.

https://www.baeldung.com/spring-boot-swagger-jwt

 

Set JWT with Spring Boot and Swagger UI | Baeldung

Learn how to set a JSON Web Token on requests to Swagger UI running in Spring Boot.

www.baeldung.com

 

아무 세팅하지 않는 swagger 에는 authorize 를 할 수 없다.

아래의 코드를 config 에 추가해주면 토큰 인증이 필요한 경우, 토큰을 저장시켜 swagger 에서 사용이 가능하다.

 

@Configuration
@RequiredArgsConstructor
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig implements WebMvcConfigurer {
    /**
     * http://localhost:8080/swagger-ui/index.html 접속
     */

    private final TypeResolver typeResolver;
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()) // Swagger UI 로 노출할 정보
                .securityContexts(List.of(securityContext()))
                .securitySchemes(List.of(apiKey()))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.project.shop")) // api 스펙이 작성되어 있는 패키지 (controller)
                .paths(PathSelectors.any()) // apis 에 위치하는 API 중 특정 path 를 선택
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
              	/**
                  * swagger 에 나타낼 필요정보 기입
                **/
                Collections.emptyList());
    }


    // swagger 에 토큰 인증 기능 추가  apiKey() , securityContext(), defaultAuth()
    private ApiKey apiKey() {
        return new ApiKey("JWT", "Authorization", "header");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder().securityReferences(defaultAuth()).build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
    }

}

 

적용 후 재실행을 하고 swagger 에 들어가면 해당 버튼이 생긴 것을 확인할 수 있다.

클릭 하면 아래와 같은 화면이 나오는데, value 값에 Bearer [토큰값] 을 넣어 실행해주었다.

EX ) Bearer 1234g1jhk234g1guiasdfiuh213iu4jasdkj12

 

 

728x90