I'm working on Web API, currently, I just want to learn about Swagger API how's it good in documentation unit test. I found this to a reference online. Can you help me how to secure Swagger API UI from accessing by an anonymous user or public user? Just designated to an authorized user only.
-
please see https://stackoverflow.com/questions/41295887/add-authentication-to-swagger-ui-index-page-swagger-web-api-swashbuckle?noredirect=1&lq=1 – stefmex Aug 27 '19 at 18:00
2 Answers
You can add an global authentication filter so that all requests will go through that filter.When you need to exclude any controller you can use [AllowAnonymous]
.
Restricting all and excluding only needed is one of the best practice in the industry.
If you are using ASP.Net Web Api
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new IdentityBasicAuthenticationAttribute());
// Other configuration code not shown...
}
You can read more about it from this link of Microsoft documentation
If you are using ASP.Net Core you may need to create a middleware. According to Asp.Net Core Documentation about Middleware
Middleware is software that is assembled into an application pipeline to handle requests and responses. Each component:+ Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline is invoked.
In the middleware check whether the user is authenticated if so proceed with next();
if not authenticated issue an Authentication.ChallengeAsync();
Add the middleware after useAuthenticaion but before useSwagger in the pipeline.

- 989
- 11
- 16
-
nice answer for web APIs! but I want to tell if someone is not authorized to access the Swagger UI it will redirect to 404 or unauthorized access page. thanks mate! – Fred Nov 10 '17 at 02:20
You can host the SwaggerUI as a separate instance in IIS and apply appropriate Authorization policy through IIS.

- 2,953
- 3
- 22
- 34