Swagger ошибка 403

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.

Here is what my SwaggerConfig.cs looks like:

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

namespace With.Api
{
    public class SwaggerConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            config.EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", "With.Api");
            })
            .EnableSwaggerUi();
        }
    }
}

Irvin Dominin's user avatar

asked Jan 23, 2016 at 23:10

Chris Knight's user avatar

Chris KnightChris Knight

1,4381 gold badge15 silver badges21 bronze badges

5

I just had the same problem. It worked fine when I deployed my app to Azure, but when I started it locally, Swagger just wouldn’t show up just as described above.
Reverting to a previous version I knew was working before also didn’t help, so it seemed to have something to do with IIS express. I’m not entirely sure what was causing the issue (I had changed some SSL related settings), but when I deleted the .vs folder (which contains the applicationhost.config file) and restarted Visual Studio, it started working again.

answered Mar 21, 2017 at 7:18

Daniel Sklenitzka's user avatar

1

It’s an old question, but it would be helpful for someone facing the same problem

If your project has a folder named swagger at root level, it conflicts and you will be not able to access swagger by hostname/swagger.

The solution is to just rename the Swagger folder to another name, then it works.

user2246521's user avatar

answered Dec 20, 2018 at 6:27

Gajendra's user avatar

3

I was having the same issue. After trying few things it still didn’t work.
Then, I tried changing the Web API application port number as suggested at the link below and it worked. I’m not sure what caused the issue.

https://github.com/domaindrivendev/Swashbuckle/issues/618

answered Aug 24, 2018 at 10:45

albtvenki's user avatar

albtvenkialbtvenki

1801 silver badge4 bronze badges

0

Coming at you in 2021 / 2022, this is a fun one.

If you are on macOS, Apple’s new airplay feature is on by default and listens to ports 5000 and 7000… sigh. Bad clash with the default swagger port (also 5000)!

Just go to System Preferences > Sharing > Uncheck «AirPlay Receiver» at the bottom of the list. Then restart your .NET application, and the Swagger UI should finally be showing up again in your browser!

Hoping this helps anyone who runs into this weird issue!

answered Feb 26, 2022 at 10:45

fullStackChris's user avatar

fullStackChrisfullStackChris

1,2501 gold badge12 silver badges24 bronze badges

1

I have this issue and it’s route and static directory conflict.
For Web Api 2, make sure you don’t have a static folder named ‘swagger’.
For .NET Core, remove folder named ‘swagger’ in wwwroot.

answered Jul 27, 2019 at 19:13

hubert17's user avatar

hubert17hubert17

2865 silver badges8 bronze badges

Try with this URL, http://mybaseurl/swagger/ui/index instead of http://mybaseurl/swagger/

answered Jan 23, 2016 at 23:46

Martin's user avatar

MartinMartin

6345 silver badges11 bronze badges

7

By some reason changing the order of calls in Application_Start, will fix the problem, this is what I have:

AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
**GlobalConfiguration.Configure(SwaggerConfig.Configure);**
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);  
XmlConfigurator.Configure();

answered May 4, 2017 at 19:38

german1311's user avatar

This solved me in .net core web api

install this nuget package Microsoft.AspNetCore.StaticFiles

answered Aug 15, 2018 at 0:15

Gomes's user avatar

GomesGomes

3,31024 silver badges17 bronze badges

@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.

Springboot + swagger2 reports error 403 Forbidden

Error reporting reason

When creating a springboot project, if spring security dependencies are introduced into the POM file, after spring boot starter security, springboot will enable authentication by default, and also enable CSRF (Cross Site Request Forgery Prevention) verification by default. Therefore, the post request will be intercepted, that is, an error 403 Forbidden will be reported, and the get request will not be intercepted

Solution

Use ignore to ignore interception and manually turn off CSRF protection. Remember to turn on annotation @ enablewebsecurity manually

@EnableWebSecurity
public class WebSecurityCongfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
    }
}

Read More:

Понравилась статья? Поделить с друзьями:
  • Sw2701 12 код ошибки
  • Sw19 ru коды ошибок
  • Sw0100 ошибка fanuc
  • Sw0100 parameter enable switch on ошибка
  • Sv0366 fanuc ошибка