【问题标题】:Configure swagger with JWT使用 JWT 配置 swagger
【发布时间】:2018-10-08 05:38:29
【问题描述】:

我想为我的 SpringBoot 应用程序安装 SWAGER。似乎 JWT 不授予对 swagger URL 的访问权限。

我正在尝试通过 url localhost:8088/swagger-ui.html 达到此目的

这里是 SwaggerConfig 类

@EnableSwagger2
@Configuration
public class SwaggerConfig {


@Bean
public Docket productApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("Path.to.my.controller"))

            .build();

}


}

我还试图从link 添加 WebAppConfig 和下一个内容

@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {

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

}

并尝试设置忽略url:

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**");
}

}

这个版本的代码可以从 swagger url 自动重定向到“localhost:8088/login”。但下一个只返回空页面

更新

  web.ignoring().antMatchers("/", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");

间隙中的网址是我在调试问题时看到的网址。这个 url 是由 swagger 调用的。

更新部分结束

主类

 @SpringBootApplication
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
    TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
    SpringApplication app = new SpringApplication(Application.class);
    app.run();
}

@Bean
@Autowired
public FilterRegistrationBean jwtFilterRegistration(JwtUtil jwtUtil, UserService userService) {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setFilter(new JwtFilter(jwtUtil, userService));

    filterRegistrationBean.addUrlPatterns("/*");

    // ordering in the filter chain
    filterRegistrationBean.setOrder(1);
    return filterRegistrationBean;
}

// Request Interceptor for checking permission with custom annotation.
@Bean
public MappedInterceptor PermissionHandlerInterceptor() {
    return new MappedInterceptor(null, new PermissionHandlerInterceptor());
}

}

Pom xml 包含所有需要的依赖项。当我在 Main 类 jwt 方法中发表评论时,我可以访问 swagger。所以我得出了JWT中的问题的结论。 如果需要一些额外的信息,我会添加。

更新

起初 swagger-url 给白标页面一个错误“未授权” 在对代码进行一些操作后,它会给出空白页。

【问题讨论】:

  • 不确定,打错了,你的链接:localhost:8088/swagger-ui.hmtl,检查html部分,否则可以检查你的代码
  • 我更新了一点。是的,这是一个错字

标签: java spring-boot jwt swagger


【解决方案1】:

我最近也不得不这样做。您需要告诉 Spring Security 允许所有 Swagger 资源。试试这个:

 @Override
 protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()


.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

            // don't create session

.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()          

            .authorizeRequests()

            // allow anonymous resource requests
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/v2/api-docs",           // swagger
                    "/webjars/**",            // swagger-ui webjars
                    "/swagger-resources/**",  // swagger-ui resources
                    "/configuration/**",      // swagger configuration
                    "/*.html",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js"
            ).permitAll()
            .antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated();

    // Custom JWT based security filter
    httpSecurity
            .addFilterBefore(authenticationTokenFilter, 
UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    httpSecurity.headers().cacheControl();
}

这是我的 Swagger 案卷配置。如果您想将令牌应用于所有端点,它还包括授权标头。

@Bean
public Docket newsApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(Lists.newArrayList(apiKey()))
            .securityContexts(Lists.newArrayList(securityContext()))
            .apiInfo(generateApiInfo());
}

@Bean
SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Lists.newArrayList(
            new SecurityReference("JWT", authorizationScopes));
}

private ApiKey apiKey() {
    return new ApiKey("JWT", "Authorization", "header");
}

【讨论】:

  • 完美运行,我不得不忽略在 antMatcher 数组中添加 HttpMethod.GET ,因为它给出了错误
猜你喜欢
  • 2019-04-24
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
相关资源
最近更新 更多