authentication.net-coreazure-active-directoryswaggerswashbuckle

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


Solution

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

    "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));