我开发了一个带有spring boot和oauth2的演示应用程序。我有三个申请如下。
我有几个可以公开访问的资源(控制器)。但是,当我试图访问swagger ui时,它会要求我进行完整的身份验证。当我添加以下代码时,swagger页面即将到来,但不仅在整个页面中有一个下拉列表,而且还打破了。
http
.anonymous() //allow anonymous access
.and()
.authorizeRequests()
.antMatchers("/shouldbepublic/**", "/swagger-ui**/**").permitAll().and() //this should be public resources
.formLogin().loginPage("/login").permitAll()
.and()
.requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
.and()
.authorizeRequests().anyRequest().authenticated();
答案 0 :(得分:1)
这是一个适合我的配置:
.antMatchers("/swagger-ui.html","/swagger-resources/**", "/v2/api-docs/**").permitAll()'.antMatchers("/swagger-ui.html","/swagger-resources/**", "/v2/api-docs/**").permitAll()
没有它,无法显示swagger-ui.html
完整的ResourceServiceConfiguration
可以在这里找到:
@Configuration
@EnableResourceServer
public static class ResourceServiceConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http.csrf().disable().authorizeRequests()
// This is needed to enable swagger-ui interface.
.antMatchers("/swagger-ui.html","/swagger-resources/**", "/v2/api-docs/**").permitAll()
.antMatchers("/**").hasAuthority("ADMIN");
// @formatter:on
}
}
答案 1 :(得分:0)
另一个选项(如果它对您来说是安全的)是让Spring Security完全忽略/swagger-ui
路径。
在您的安全@Configuration
文件扩展WebSecurityConfigurerAdapter
中添加以下内容:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.GET, "/swagger-ui/**");
super.configure(web);
}
答案 2 :(得分:0)
如果您使用的是Swagger2,请尝试许可:
http.authorizeRequests().antMatchers("/configuration/**","/swagger**","/webjars/**","/v2/**").permitAll();
让它发挥作用。
答案 3 :(得分:0)
就我而言,使用Spring Security 5和OAuth2以及Spring Actuator和Swagger / Swagger-UI,我必须使用此类覆盖Spring Security:
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(final HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests()
.antMatchers(
"/",
"/actuator/**",
"/v2/api-docs/**",
"/swagger-ui.html",
"/swagger-resources/**",
"/webjars/**"
)
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
;
}
}