Swagger ошибка 403

I’m using spring boot and I’ve added swagger to my dependencies:

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

My configuration:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

When I go this url:

http://localhost:8080/v2/api-docs it works and I get the json back.

The swagger ui http://localhost:8080/swagger-ui.html

Is just an empty page now when I inspect the network tab in chrome I see this:

Failed to load resource: the server responded with a status of 403 ()
swagger-ui-standalone-preset.js Failed to load resource: the server responded with a status of 403 ()
swagger-ui.css Failed to load resource: the server responded with a status of 403 ()
springfox.js Failed to load resource: the server responded with a status of 403 ()
swagger-ui-bundle.js Failed to load resource: the server responded with a status of 403 ()
swagger-ui-standalone-preset.js Failed to load resource: the server responded with a status of 403 ()
springfox.js Failed to load resource: the server responded with a status of 403 ()
webjars/springfox-swagger-ui/favicon-32x32.png?v=2.8.0-SNAPSHOT Failed to load resource: the server responded with a status of 403 ()
webjars/springfox-swagger-ui/favicon-16x16.png?v=2.8.0-SNAPSHOT Failed to load resource: the server responded with a status of 403 ()
springfox.css Failed to load resource: the server responded with a status of 403 ()
swagger-ui.css Failed to load resource: the server responded with a status of 403 ()

I’m using spring boot security and I added this to my security configuration:

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

Can somebody help me?

asked Feb 1, 2018 at 16:52

user1007522's user avatar

user1007522user1007522

7,87817 gold badges69 silver badges113 bronze badges

2

Try adding the following resources in the ignored list,

  • /swagger-resources/**
  • /webjars/**

Here is the complete example,

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

answered Feb 1, 2018 at 19:01

Indra Basak's user avatar

5

You have to explicit ignore all your required static resources for swagger in your Spring Security Configuration. The error message you get from the network tab indicates that the browser is able to load the swagger-ui.html file but is unable to load the related .js/.css/images/iconsbecause they are not ignored in your Security Configuration.

Try this solution:

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

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

}

Related stackoverflow post: How to configure Spring Security to allow Swagger URL to be accessed without authentication

answered Feb 1, 2018 at 18:59

rieckpil's user avatar

rieckpilrieckpil

10.5k3 gold badges32 silver badges56 bronze badges

1

What I was missing was extending the WebMvcConfigurationSupport in the Swagger config and Overriding the addResourceHandlers method as below:

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport{

    @Bean
    public Docket api() {

    }

    private ApiInfo metadata() {
    }

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

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

answered Aug 25, 2018 at 13:59

joeabala's user avatar

joeabalajoeabala

2663 silver badges11 bronze badges

@joebala answer worked for me too. But if you want implements instead of extends, you can use WebMvcConfigurer interface:

public class SwaggerConfig implements WebMvcConfigurer {

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

// your other configuration
}

answered Jun 5, 2021 at 12:08

Azer Abishov's user avatar

@cknightdevelopment

I am trying to use Swagger with Web API. I am just using the «Azure API App» template from the ASP.NET 4.6 templates installed with Visual Studio, which includes the Swashbuckle.Core and the SwaggerConfig.cs. The API works fine (I am able to call it successfully), but if I try to go to «http://mybaseurl/swagger/», I get this error:

HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.

It seems like Swagger is not getting loaded or something. Anyone else get this before? I can’t seem to get around this. Thank you, and please let me know if I can provide more details.

@domaindrivendev

Perhaps the Swagger routes aren’t getting registered with your WebAPI. I’ve seen this happen with certain deployment setups due to the use of WebActivatorEx. You can bypass this and register manually by removing the following line in SwaggerConfig.cs:

[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

And then invoking the Register method directly in your global.asax:

protected void Application_Start()
{
    SwaggerConfig.Register();            
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

Give it a try and let me know if this helps?

@rfcdejong

I have the same Issue, started on ASP.NET Core 1.0 and everything worked fine. Because of a .NET 2 dependency we needed to step back to ASP.NET MVC 5.0 and now I run into this error. The suggestion to place this in the Application_Start or in my case OwinStartup didn’t fix the 403.14 error.

@rfcdejong

Swagger is loaded, when I type in …/swagger it redirect to …/swagger/ui/index and it shows the 403.14 error. If I type in …/docs/v1 it shows: {«swagger»:»2.0″,»info»:{«version»:»v1″,»title»:»My Title»},»host»:»localhost:3897″,»schemes»:[«http»],»paths»:{},»definitions»:{}}

@rfcdejong

Oke… really strange, I played a bit with switching hosted environments, from IIS Express to Local IIS and even self-hosted OWIN in a cmd prompt. Now back to IIS Express (another port!) and it suddenly works… I have no clue why it didn’t work before as it’s the same code…

@domaindrivendev

Are you happy to close this issue?

@rfcdejong

Perhaps the topic starter ‘cknightdevelopment’ will never answer back. I hope my comments help someone in the future. Just close it as issue ;)

@codepm

I have a similar issue… except that the 403.14 error occurs when I try using just /swagger. If I type the full path /swagger/ui/index it resolves. Any ideas?

@gzepeda

I have the same issue right now. None of the workarounds have worked. I do not get redirected to ui/index, just get the forbidden message.

Any help is greatly appreciated.

@Leftyx

You can always specify the startup url and things should work properly.

swashbuckle

@kinglywork

just for sharing: for the HTTP Error 403.14 — Forbidden, either of these works for me:

  1. change project url to another port(Project Properties -> Web -> Project Url)
  2. specify a base url for EnableSwaggerUi(«docs/{*assetPath}»)

but still not know the reason of 403 error

@emsiu

Sharing this fix as well for «HTTP Error 403.14 — Forbidden» that worked for me:

Delete the .vs folder that contains the applicationhost.config file and restart Visual Studio before trying to use Swagger again.

@RyanONeill1970

Another reason that this happens;

Developing locally with IIS / IIS Express and SSL, all works. When publishing to Azure (or probably anywhere else) you get a 403 Forbidden when trying to request a JWT token (or access the anonymous login endpoint).

Took me a while to find the answer, but publishing to Azure created a HTTPS capable website, unfortunately it launched the HTTP version in my browser which fails with 403 FORBIDDEN, even though the UI came up at /swagger.

Quick answer, make sure you are using HTTPS on your dev, test and live site urls.

@rago99

If someone has this problem of «403.14 — Forbidden» when using «/swagger», but the use of the full path «/swagger/ui/index» works.
In my case, after having spent too much time looking for a solution and none worked, in the end the problem was simpler that I thought, I had a folder called swagger in the solution, when I changed the name to something else the problem was solved.
I hope this can prevent someone’s headaches

@Hiunkeru

@argelj289

I am also having the same issue

And none of the solutions above worked on my side.

Are there latest approach that could help fix it?

#openapi #swaggerhub

Вопрос:

У меня есть следующее определение OpenAPI, размещенное на SwaggerHub:
https://app.swaggerhub.com/apis/MyFirstAPI/1.0.1-oas3

 openapi: 3.0.0
servers:
  - url: http://api.myfirstapi.com/
info:
  version: 1.0.1-oas3
  title: Equ API
paths:
  /query:
    get:
      tags:
        - developers
      parameters:
        - in: query
          name: searchString
          schema:
            type: string
      responses:
        '200':
          description: search results matching criteria
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Equity'
        '400':
          description: There is 400
components:
  schemas:
    Equity:
      ...
 

Когда я проверяю GET /query запрос, он возвращает ошибку 403:

 content-length: 0 
date: Fri,10 Sep 2021 14:32:54 GMT 
server: nginx/1.18.0   Phusion Passenger(R) 6.0.8 
status: 403 Forbidden 
via: 1.1 b5d86079363e9709b4c4051d3c94ac3d.cloudfront.net (CloudFront) 
x-amz-cf-id: pYbLwlrEHg5DXkGe5FkysAjSjbSDqUg7Rrhbv-Dt8Xwt8JuPRMAW3Q== 
x-amz-cf-pop: DEL54-C1 
x-cache: Error from cloudfront 
x-powered-by: Express,Phusion Passenger(R) 6.0.8
 

Почему возникает эта ошибка и как ее исправить?

Комментарии:

1. Нужно больше деталей. Какой инструмент вы используете для тестирования пользовательского интерфейса запроса — Swagger, Почтальон, что-то еще? Если API, который вы тестируете, является общедоступным — пожалуйста, добавьте URL-адрес запроса и параметры в свой вопрос. Ответ 403 указывает на ошибку разрешения — вы включили в запрос правильную информацию для аутентификации?

Ответ №1:

Эта ошибка 403 несколько вводит в заблуждение. Фактическая проблема здесь заключается в том, что целевой сервер для запросов api.myfirstapi.com — на самом деле не существует. В servers списке должен быть указан ваш реальный сервер(ы).

Если вы разрабатываете новый API и у вас еще нет живого сервера, вы можете использовать макет сервера SwaggerHub для сравнения ответов и тестирования вызовов API.

Чтобы добавить макет в определение API:

  1. Щелкните имя API на панели инструментов редактора.
  2. Перейдите на вкладку Интеграции и нажмите Добавить новые интеграции. SwaggerHub: Добавление новой интеграции на уровне API
  3. Выберите Автоматическое издевательство над API из списка и нажмите Добавить.
  4. Введите любое значение для Имени (например, макет), оставьте другие параметры как есть и нажмите Создать и выполнить.
  5. Закройте оставшиеся диалоговые окна.

Это создает макет сервера для вашего API и добавляет его в servers список в определении вашего API:

 servers: 
  - description: SwaggerHub API Auto Mocking
    url: https://virtserver.swaggerhub.com/OWNER_NAME/API_NAME/VERSION
 

Обязательно выберите этот сервер в документах API, прежде чем тестировать вызовы API.

Макет сервера SwaggerHub в списке серверов в интерактивных документах API

Issue :
Get request for Swagger UI openAPI is working , whereas other method types giving 403 error.

Dependency :

<dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.6.6</version>
</dependency>

Swagger Configuration :

@Configuration
@OpenAPIDefinition(servers = {
        @Server(url = "https://hostname")
})
@SecurityScheme(name = auth, type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer")
public class SwaggerConfig {
}

Security Configuration :

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .anyRequest().authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/swagger-ui/**","/v3/api-docs/**");
        }
    }

We have also tried ignoring these paths : /swagger-resources/** , /webjars/** in WebSecurity, still its not working.

Post Request Error message 403

Original Edit : On some further research , found that’s it may be because of the nginx proxy. Everything is working fine on my local but not working on other environments that are hosted behind the nginx proxy.

I have migrated to Spring Boot version 3 from 2.7 and Swagger UI stopped working.

Below are the dependencies I have used:

spring-boot-starter-parent – 3.0.0
springfox-boot-starter-3.0.0
springdoc-openapi-starter-webmvc-ui – 2.0.2
springdoc-openapi-core – 1.1.49

I have configured the following property in application.properties:

springdoc.api-docs.path=/api-docs

but I am still getting 403 error while opening Swagger UI in the bowser (http://localhost:8080/swagger-ui/index.html):

websecurityconfig class made the Swagger UI URL as public with the following code:
java
String[] PUBLIC_URL = {"/v3/api-docs",
"/v2/api-docs", "/swagger-resources/",
"/swagger-ui/
",
"/swagger-ui.html",
"/v3/api-docs/",
"/api-docs/
",
"api-docs" }
http.authorizeHttpRequests().requestMatchers(PUBLIC_URL).permitAll();

Понравилась статья? Поделить с друзьями:
  • Swot анализ ошибки
  • System pte misuse ошибка windows 10 при установке
  • System overflowexception ошибка переполнения
  • Swtor русификатор ошибка необрабатываемое исключение
  • System fault service now touareg ошибка