我知道可以在 spring-boot
应用程序上使用 @Profile
完全禁用 swagger-ui
,但我仍然需要某些特权用户能够访问 swagger-ui 且未完全禁用。
有没有办法实现这一点。
更新:
目前我正在使用拦截器
方法,但我不想要这种方法。
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
if(request.getRequestURI().contains("swagger") &&
!request.isUserInRole("XX_YY_ZZ")) {
response.sendError(403, "You are not authorized to access "); }
return super.preHandle(request, response, handler);
}
最佳答案
如果没有您使用的版本或代码,很难提供帮助。但我会尽力而为。
当您使用 swagger-ui 时,您有一个公开的 URL 来访问您的文档(通常为 /swagger-ui.html
)。
您正在使用spring-boot
,并谈论用户限制,所以我假设您可以使用spring-boot-starter-security
。
使用 spring-boot-starter-security
,您可以轻松配置要保护的 URL(例如,关于用户角色)。
这是一个有效的示例配置:
@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// the rest of your configuration
http.authorizeRequests().mvcMatchers("/swagger-ui.html").hasRole("DEVELOPER")
}
您可以保护 swagger URL,就像使用 Controller 公开的任何 URL 一样。
了解更多信息:
- 类似的问题: How to configure Spring Security to allow Swagger URL to be accessed without authentication
- Spring 安全配置: https://spring.io/guides/gs/securing-web/
我可以在以下方面提供更多帮助:
- 安全配置摘录
- 您正在使用的 Spring-boot 版本
关于java - 根据角色禁用 swagger-ui,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59503245/