限制访问Swagger-UI.html - Spring MVC 安全配置

您可以通过以下方式限制访问'swagger-ui.html':

  1. 使用 Spring Security 拦截器

WebSecurityConfigurerAdapter 中添加以下代码:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/swagger-ui.html").hasRole("ADMIN")
        .anyRequest().permitAll()
        .and()
        .formLogin().permitAll()
        .and()
        .logout().permitAll();
}

此配置将只允许具有'ADMIN'角色的用户访问'swagger-ui.html'。

  1. 使用 Spring MVC 拦截器

WebMvcConfigurer 中添加以下代码:

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new HandlerInterceptorAdapter() {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String requestUri = request.getRequestURI();
            if (requestUri.endsWith("/swagger-ui.html") && !request.isUserInRole("ADMIN")) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
            return true;
        }
    });
}

此配置将只允许具有'ADMIN'角色的用户访问'swagger-ui.html',并在其他情况下返回HTTP 403 Forbidden响应。

通过以上两种方法,您可以轻松地限制对Swagger-UI.html的访问权限,提高应用程序的安全性。


原文地址: https://www.cveoy.top/t/topic/lMZK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录