带有Spring安全性的Swagger-ui [英] Swagger-ui with Spring security

查看:670
本文介绍了带有Spring安全性的Swagger-ui的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有身份验证服务的简单REST应用程序.我试图向其中添加swagger和swagger-ui,但是我只能在/v2/api-docs中看到端点. 在swagger-ui.html中,我仅看到端点组,但是无法扩展任何列表.

I have a simple REST application with authentication service. I tried to add swagger and swagger-ui to it, but I can only see my endpoints in /v2/api-docs. In swagger-ui.html I see only groups of endpoints but I am unable to extend any list.

在chrome调试中,我看到:

In chrome debug I see:

无法加载资源:服务器的响应状态为401()

Failed to load resource: the server responded with a status of 401 ()

未捕获的TypeError:无法读取未定义的属性'indexOf'

Uncaught TypeError: Cannot read property 'indexOf' of undefined

并在带有服务器的终端上:

and on a terminal with a server:

错误10020-[nio-5001-exec-3] c.t.r.a.p.JwtAuthenticationEntryPoint:响应未经授权的错误.消息-访问此资源需要完整身份验证

ERROR 10020 --- [nio-5001-exec-3] c.t.r.a.p.JwtAuthenticationEntryPoint : Responding with unauthorized error. Message - Full authentication is required to access this resource

我的配置文件似乎丢失了一些东西,我尝试了一些在网络上找到的解决方案,但仍然无济于事.

It looks like my config files are missing something, I tried few solutions I found on a web but still nothing work.

这是我的代码:

pom

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

控制器

@RestController
@PreAuthorize("hasRole('USER')")
@RequestMapping(path = "restaurant")
@Api(value="restaurant", description="Example operations for restaurants")
public class RestaurantController {
// endpoints
}

s豆

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.tablebooker.restaurantservice.restaurant"))
                .paths(PathSelectors.any())
                .build();
    }
}

SecurityConfig

SecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//other methods

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/",
                        "/favicon.ico",
                        "/**/*.png",
                        "/**/*.gif",
                        "/**/*.svg",
                        "/**/*.jpg",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js")
                .permitAll()
                .antMatchers("/api/auth/**")
                .permitAll()
                .antMatchers("/restaurant/**")
                .hasRole("USER")
                .anyRequest()
                .authenticated();

        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");
    }
}

有什么想法可以使我的配置正常工作吗?

Any ideas how can I make my configuration work?

推荐答案

首先,您应该注册swagger的资源.

First you should registry swagger's resources.

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}

然后因为您正在使用Spring Security,也许您应该关闭特权.

Then cause you're using Spring Security,maybe you should shutdown privileges.

   @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers(HttpMethod.OPTIONS, "/**");
        // ignore swagger 
        web.ignoring().mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs");
    }

也许最好使用版本低于2.8.0的swagger,否则您可能不得不面对许多错误.

And maybe it's better for you to use swagger which the version is under 2.8.0,or you may have to face to lots of bugs.

这篇关于带有Spring安全性的Swagger-ui的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆