BACKEND/Spring
SpringBoot Swagger2 UI์ JWT ํ ํฐ Authorize ๋ฒํผ ๋ฃ๊ธฐ
์ก์ด ๐ซง
2022. 2. 22. 21:12
** ๊ธฐ๋ณธ์ ์ผ๋ก security ์ค์ ๊ณผ swagger ์ค์ ์ด ๋ค ๋์ด์์์ ๋ฐํ์ผ๋ก ํ๋ค.
SwaggerConfig.java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.cherishpet.backend"))
.paths(PathSelectors.ant("/api/**"))
.build()
.apiInfo(metaData())
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Arrays.asList(apiKey()));
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("CherishPet REST API")
.description("CherishPet rest api documentation")
.license("Apache License Version 2.0")
.build();
}
private ApiKey apiKey() {
return new ApiKey("JWT", "Authorization", "header");
}
private SecurityContext securityContext() {
return springfox
.documentation
.spi.service
.contexts
.SecurityContext
.builder()
.securityReferences(defaultAuth()).forPaths(PathSelectors.any()).build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
}
}
์ฌ๊ธฐ์ apiKey()ํจ์์์ ๋ฆฌํดํ๋ new ApiKey("JWT", "Authorization", "header") ์ "Authorization"์ ํค๋์์ JWT ํ ํฐ ๊ฐ์ ๊ฐ์ ธ์ฌ๋ ์ง์ ํด ๋์ key ์ด๋ฆ๊ณผ ๊ฐ์์ผํ๋ค.
******
security ์ค์ ์์ HttpServletRequest ๊ฐ์ฒด์์ ํค๋(ํ ํฐ)๋ฅผ ๊ฐ์ ธ์ฌ ๋
์ด๋ค ์ด๋ฆ์ผ๋ก getHeader("์ ํด๋์ ํค์ด๋ฆ")๋ฅผ ํ๋์ง ํ์ธํ์!!!
******