如何解决将 Swagger UI 限制为特定角色
我试图将 Swagger 用户界面 (UI) 的访问权限限制为特定角色(例如 Swagger API 用户、系统管理员用户等...)
我在这个 SO 问题中尝试了答案 - Restrict access to Swagger UI
所以我的代码类看起来像
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* XLogger.
*/
private static final XLogger LOG = XLoggerFactory.getXLogger(WebSecurityConfig.class);
@Value("${my.property.allowedOrigins}")
private String[] corsAllowedOrigins;
@Value("${my.property.excludeUrlPattern}")
private String[] excludeUrlPattern;
@Autowired
ApplicationContext applicationContext;
/**
* The AuthenticationSuccessHandler.
*/
@Autowired
HSSAuthenticationSuccessHandler authenticationSuccessHandler;
/**
* The runtime properties
*/
@Autowired
RuntimeProperties runtimeProperties;
@Override
protected void configure(HttpSecurity http) throws Exception {
LOG.entry(http);
String[] noAuthPermitAllPatterns = runtimeProperties.getApplicationProperties().getNoAuthPermitAllPatterns();
http.authorizeRequests()
.antMatchers("/swagger-ui/**","/**/swagger-ui/**","/v3/api-docs/**","/**/v3/api-docs/**")
.hasRole("ADMIN").antMatchers(noAuthPermitAllPatterns).permitAll().anyRequest().authenticated().and()
.formLogin().failureHandler(authenticationFailureHandler()).successHandler(authenticationSuccessHandler)
.loginPage("/saml/login").permitAll().and().logout().logoutSuccessUrl("/logoutSuccess").permitAll()
.invalidateHttpSession(true).and().csrf().disable().cors()
.configurationSource(corsConfigurationSource());
http.addFilterBefore((MetadataGeneratorFilter) applicationContext.getBean("MetadataGeneratorFilter"),ChannelProcessingFilter.class).addFilterafter(
(FilterChainProxy) applicationContext.getBean("samlFilter"),BasicAuthenticationFilter.class);
LOG.exit();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
LOG.entry();
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList(corsAllowedOrigins));
configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT"));
configuration.setAllowCredentials(true);
// the below three lines will add the relevant CORS response headers
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",configuration);
return LOG.exit(source);
}
@Override
@Bean(name = "webAuthenticationManagerBean")
public AuthenticationManager authenticationManagerBean() throws Exception {
LOG.entry();
return LOG.exit(super.authenticationManagerBean());
}
/**
* Authentication Failure Handler
*
* @return The Authentication Failure Handler
*/
@Bean(name = "authenticationFailureHandler")
protected AuthenticationFailureHandler authenticationFailureHandler() {
LOG.entry();
String defaultFailureUrl = runtimeProperties.getApplicationProperties().getDefaultFailureURL();
ExceptionMappingAuthenticationFailureHandler authFailureHandler = new ExceptionMappingAuthenticationFailureHandler();
authFailureHandler.setDefaultFailureUrl(defaultFailureUrl);
Map<String,String> mappings = new HashMap<>();
mappings.put("org.springframework.security.authentication.InternalAuthenticationServiceException",defaultFailureUrl);
mappings.put("org.springframework.security.saml.SAMLAuthenticationToken",defaultFailureUrl);
mappings.put("org.springframework.security.authentication.AuthenticationServiceException",defaultFailureUrl);
authFailureHandler.setExceptionMappings(mappings);
return LOG.exit(authFailureHandler);
}
@Override
public void configure(WebSecurity web) throws Exception {
LOG.entry(web);
web.ignoring().antMatchers(excludeUrlPattern);
LOG.exit();
}
}
这仍然允许我访问 Swagger UI @
http://{localUrl}/swagger-ui/index.html?configUrl=/{localUrl}/v3/api-docs/swagger-config
另外,两个 configure() 方法有什么区别,一个使用 HttpSecurity
,另一个使用 WebSecurity
? excludeUrlPattern 确实包含 swagger 模式,所以我想知道这是否会与我尝试做的事情产生冲突。
我想我在期待 401 未经授权的响应。我对 Swagger 完全陌生,因此感谢您提供任何建议!
解决方法
与其他端点相同。这仍然会让其他人下载 swagger 配置,如果您确实需要该级别的控制,您也可以阻止 /api-docs/**
。
...
.antMatchers("/swagger-ui/**") // For URI starting with swagger-ui
.hasRole("USER")
.antMatchers("/**/swagger-ui/**") // For URI that contains swagger-ui
.hasRole("USER")
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。