Настроить чванство с JWT - PullRequest
       9

Настроить чванство с JWT

0 голосов
/ 27 апреля 2018

Я хочу установить SWAGER для моего приложения SpringBoot. Кажется, что JWT не дает доступ к чванливым 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();

}


}

Также я пытался добавить 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/**");
}

}

Эта версия кода дает автоматическое перенаправление на "localhost: 8088 / login" с URL-адреса swagger. Но следующая возвращает просто пустую страницу

ОБНОВЛЕНО

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

URL-адреса в пробелах - это URL-адреса, которые я видел, когда выполнял отладку. Эти URL называются чванством.

ОБНОВЛЕННАЯ часть Конец

Основной класс

 @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 содержит все необходимые зависимости. Когда я комментирую в методе jwt Главного класса, я могу получить доступ к чванству. Итак, я сделал вывод, что проблема в JWT. Если потребуется дополнительная информация, я добавлю.

ОБНОВЛЕНО

Сначала swagger-url выдает White Label Page с ошибкой "Unathorized" После некоторых манипуляций с кодом выдает пустую страницу.

1 Ответ

0 голосов
/ 20 декабря 2018

Мне недавно пришлось сделать то же самое. Вы должны сообщить своей 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");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...