일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 그리드 알고리즘
- 컴퓨터 네트워크
- 알고리즘
- github action
- 다이나믹프로그래밍
- 백준
- Spring
- dfs
- 도커
- 순열
- 브루트포스
- 분할 정복
- SQL
- 자료구조
- 분할정복
- 그래프
- TCP
- 스프링
- 그리드
- AWS
- 트리
- 자바
- 이분탐색
- CI/CD
- BFS
- GIT
- 다이나믹 프로그래밍
- 재귀
- HTTP
- 역방향 반복자
- Today
- Total
코딩성장스토리
Swagger + Security 적용 본문
팀 프로젝트를 하다가 api관리를 하면 좋겠다는 생각이 들었고 보기 편하게 되면 같이 작업하시는 분들한테도 좋고 나한테도 좋을 것이라 생각했다.
그걸 위한 Swagger가 존재한다.
심지어 설정도 매우 쉬운 편이다.
Swagger를 설정해 보자
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private final String version = "v1";
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API")
.description("설명")
.build();
}
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Arrays.asList(apiKey()))
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
.paths(PathSelectors.any())
.build()
;
}
@EnableSwagger2 -Swagger2 버전을 활성화 하겠다는 어노테이션
Docket - Swager 설정의 핵심이되는 Bean
select() - ApiSelectorBuilder를 생성
apis() -api 스펙이 작성되어 있는 패키지를 지정하여, 컨트롤러가 존재하는 패키지를 basepackage 로 지정하여, RequestMapping(GetMapping, PostMapping…)이 선언된 API를 문서화 (저 위코드에서는 com.swagger.controller 밑에 있는 모든 api 포함)
paths() -apis()로 선택되어진 API 증 특정 path 조건에 맞는 APi들을 다시 필터링하여 문서화
apiInfo()- 제목, 설명 등 문서에 대한 정보들을 보여주기 위해 호출
이런 설정만 하면 나는 오류가 나왔다..
왜냐하면 Spring security를 사용했기 때문에 swagger관련된 url을 열어줘야 했다.
그래서 SecurityConfig에 등록 ( security가 최신 버전으로 바뀌면서 기존 코드들이랑 달라 찾는데 좀 걸렸다..😂)
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers( "/swagger-resources/**",
"/swagger-ui/**",
"/v3/api-docs",
"/webjars/**");
}
그리고 나는 jwt를 통한 인증도 구현하고 있다.
그래서 swagger 내부에 인증을 담고 싶었다.
관련 된 코드
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("Authorization", authorizationScopes));
}
private ApiKey apiKey() {
return new ApiKey("Authorization", "Authorization", "header");
}
전체 코드
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private final String version = "v1";
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API")
.description("설명")
.build();
}
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Arrays.asList(apiKey()))
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
.paths(PathSelectors.any())
.build()
;
}
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("Authorization", authorizationScopes));
}
private ApiKey apiKey() {
return new ApiKey("Authorization", "Authorization", "header");
}
}
결과
권한 표시도 잘 나온다.
권한에 내가 원하는 토큰 값을 넣고 url 실행!
성공!!
'기타' 카테고리의 다른 글
CI/CD(Github action) (1) | 2023.03.27 |
---|---|
aws CloudFront + S3 (3) | 2023.02.14 |
Spring Security 공부 + Jwt 적용 (1) | 2023.01.26 |
R data 연습 다루기 (0) | 2022.10.25 |
docker 안에 있는 mariaDB 접속하기 (0) | 2022.09.15 |