使用JWT配置swagger

时间:2018-04-27 11:20:38

标签: java spring-boot jwt swagger

我想为我的SpringBoot应用程序安装SWAGER。似乎JWT不提供swagger 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/");
}

}

并尝试设置忽略网址:

@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/**");

间隙中的网址是我在看到发布时的网址。这个网址被招摇称呼。

更新部分结束

主要课程

 @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 class jwt方法中发表评论时,我可以访问swagger。所以我在JWT中得出结论。 如果需要一些额外的信息,我会添加。

已更新

首先,swagger-url给White Label Page一个错误“Unathorized” 经过一些代码操作后,它会给出空页。

1 个答案:

答案 0 :(得分:0)

我最近不得不做同样的事情。您需要告诉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");
}