인증없이 Swagger URL에 액세스 할 수 있도록 Spring Security를 구성하는 방법
내 프로젝트에는 Spring Security가 있습니다. 주요 문제 : http : // localhost : 8080 / api / v2 / api-docs 에서 swagger URL에 액세스 할 수 없습니다 . 인증 헤더가 없거나 잘못되었습니다.
브라우저 창의 스크린 샷 My pom.xml에는 다음 항목이 있습니다.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
SwaggerConfig :
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", "myeaddress@company.com", "License of API", "API license URL");
return apiInfo;
}
AppConfig :
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.musigma.esp2" })
@Import(SwaggerConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter {
// ========= Overrides ===========
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
web.xml 항목 :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.musigma.esp2.configuration.AppConfig
com.musigma.esp2.configuration.WebSecurityConfiguration
com.musigma.esp2.configuration.PersistenceConfig
com.musigma.esp2.configuration.ACLConfig
com.musigma.esp2.configuration.SwaggerConfig
</param-value>
</context-param>
WebSecurityConfig :
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = { "com.musigma.esp2.service", "com.musigma.esp2.security" })
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(this.unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/auth/login", "/auth/logout").permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().authenticated();
// custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
httpSecurity.addFilterBefore(loginFilter(), UsernamePasswordAuthenticationFilter.class);
// custom Token based authentication based on the header previously given to the client
httpSecurity.addFilterBefore(new StatelessTokenAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
}
}
이것을 WebSecurityConfiguration 클래스에 추가하면 트릭을 수행해야합니다.
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
}
나는 / configuration / ** 및 / swagger-resources / **로 업데이트했으며 저에게 효과적이었습니다.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");
}
Spring Boot 2.0.0.M7 + Spring Security + Springfox 2.8.0을 사용하여 동일한 문제가 발생했습니다. 그리고 Swagger UI 리소스에 대한 공개 액세스를 허용하는 다음 보안 구성을 사용하여 문제를 해결했습니다.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
// -- swagger ui
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**"
// other public endpoints of your API may be appended to this array
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
// ... here goes your custom security configuration
authorizeRequests().
antMatchers(AUTH_WHITELIST).permitAll(). // whitelist Swagger UI resources
// ... here goes your custom security configuration
antMatchers("/**").authenticated(); // require authentication for any endpoint that's not whitelisted
}
}
if your springfox version higher than 2.5, should be add WebSecurityConfiguration as below:
@Override
public void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.authorizeRequests()
.antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.csrf().disable();
}
Considering all of your API requests located with a url pattern of /api/..
you can tell spring to secure only this url pattern by using below configuration. Which means that you are telling spring what to secure instead of what to ignore.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
More or less this page has answers but all are not at one place. I was dealing with the same issue and spent quite a good time on it. Now i have a better understanding and i would like to share it here:
I Enabling Swagger ui with Spring websecurity:
If you have enabled Spring Websecurity by default it will block all the requests to your application and returns 401. However for the swagger ui to load in the browser swagger-ui.html makes several calls to collect data. The best way to debug is open swagger-ui.html in a browser(like google chrome) and use developer options('F12' key ). You can see several calls made when the page loads and if the swagger-ui is not loading completely probably some of them are failing.
you may need to tell Spring websecurity to ignore authentication for several swagger path patterns. I am using swagger-ui 2.9.2 and in my case below are the patterns that i had to ignore:
However if you are using a different version your's might change. you may have to figure out yours with developer option in your browser as i said before.
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
, "/webjars/**", "/csrf", "/");
}
}
II Enabling swagger ui with interceptor
Generally you may not want to intercept requests that are made by swagger-ui.html. To exclude several patterns of swagger below is the code:
Most of the cases pattern for web security and interceptor will be same.
@Configuration
@EnableWebMvc
public class RetrieveCiamInterceptorConfiguration implements WebMvcConfigurer {
@Autowired
RetrieveInterceptor validationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(validationInterceptor).addPathPatterns("/**")
.excludePathPatterns("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
, "/webjars/**", "/csrf", "/");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Since you may have to enable @EnableWebMvc to add interceptors you may also have to add resource handlers to swagger similar to i have done in the above code snippet.
'Program Tip' 카테고리의 다른 글
MongoDB C # 드라이버-바인딩시 필드 무시 (0) | 2020.12.10 |
---|---|
UIView 크기는 어떻게 변경합니까? (0) | 2020.12.10 |
Oracle에서보기 란 무엇입니까? (0) | 2020.12.10 |
NULL을 먼저 표시 한 다음 가장 최근 날짜를 보여주는 ORDER BY DATE (0) | 2020.12.10 |
& to & etc로 변환 (0) | 2020.12.10 |