Niranjan
Niranjan

Reputation: 2229

How swagger authentication works?

Hi I have developed swagger UI for my .net core web application. I have added authentication to it. I have registered two applications in my Azure AD. One for Swagger and one for Back end .Net core app. Below is my code.

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });

                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",
                    AuthorizationUrl = swaggerUIOptions.AuthorizationUrl,
                    TokenUrl = swaggerUIOptions.TokenUrl
                });
                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                        { "oauth2", new[] { "readAccess", "writeAccess" } }
                });
            });

In the above code I am indicating type and flow. Also specifying AuthorizationUrl and token url. When coming to scopes, If I add scopes then that means my Swagger has access to added scopes or my back end api has access to those scopes? Then I have below code.

c.OAuthClientId(swaggerUIOptions.ClientId);
                c.OAuthClientSecret(swaggerUIOptions.ClientSecret);
                c.OAuthRealm(azureActiveDirectoryOptions.ClientId);
                c.OAuthAppName("Swagger");
                c.OAuthAdditionalQueryStringParams(new { resource = azureActiveDirectoryOptions.ClientId });
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

When we develop swagger, We are getting access token for swagger app or back end app? Also I have c.OAuthRealm and passing my back end app client id. What this line of code do actually? Also when I add [Authorize] attribute in top of my API and then If i try to hit api directly It will not work. It will work only after authentication. So how Authorize attribute works exactly? Can someone help me to understand these things? Any help would be appreciated. Thanks

Upvotes: 1

Views: 2425

Answers (1)

Jim Xu
Jim Xu

Reputation: 23111

Regarding how to configure Swagger to authenticate against Azure AD, please refer to the following steps

  • Configure Azure AD for your web API. For more details, please refer to the document

    a. Create Azure AD web api application

    b. Expose API enter image description here

    c. Configure code

    1. config file
"AzureAd": {
 "Instance": "https://login.microsoftonline.com/",
 "ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",

 "TenantId": "<your tenant id>"
},
  1. Add following code in the Stratup.cs
 services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

  • Configure swagger. For more details, please refer to the blog.

    a. Create Azure Web application

    enter image description here enter image description here enter image description here

    b. Configure API permissions. Regarding how to configure, you can refer to the document

    c. code

    1. Install SDK
    <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
    
    1. Add the following code to Startup.cs in the ConfigureServices method:
    services.AddSwaggerGen(c =>
    {
    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    c.AddSecurityDefinition("oauth2", new OAuth2Scheme
    {
    Type = "oauth2",
    Flow = "implicit",
    AuthorizationUrl = $"https://login.microsoftonline.com/{Configuration["AzureAD:TenantId"]}/oauth2/authorize",
    Scopes = new Dictionary<string, string>
    {
     { "user_impersonation", "Access API" }
    }
    });
    c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
    {
    { "oauth2", new[] { "user_impersonation" } }
    });
    });
    
    1. Add the following code to the Configure method:
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
    c.OAuthClientId(Configuration["Swagger:ClientId"]);
    c.OAuthClientSecret(Configuration["Swagger:ClientSecret"]);
    c.OAuthRealm(Configuration["AzureAD:ClientId"]);
    c.OAuthAppName("My API V1");
    c.OAuthScopeSeparator(" ");
    c.OAuthAdditionalQueryStringParams(new { resource = Configuration["AzureAD:ClientId"] });
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
    
    

Upvotes: 1

Related Questions