Search code examples
.netazureazure-active-directoryswaggeropenapi

OpenApi - Not working Azure Ad Client Credentials


I tried logging in openapi using client credentials flow. And I can't do it. OpenApi returns me this error. I tried it in swagger as well and the result is the same. I have no idea what to do about it and I can't find much to do about it.

Thanks in advance for your helpenter image description here


Solution

  • I registered one Azure AD application and exposed an API with scope as below:

    enter image description here

    When I tried to authorize using client credentials flow, I too got same error with CORS issue for token endpoint in browser console as below:

    enter image description here

    As suggested by @juunas in this SO thread, you cannot use client credentials flow from front-end as Azure AD blocks cross origin requests to its token endpoint.

    To resolve the error, you need to switch to delegated authentication flows like implicit flow or authorization code flow that involves user interaction.

    In my case, I used implicit flow by enabling below options in my Azure AD application:

    enter image description here

    Now, I modified the code by replacing client credentials with implicit flow related parameters like this:

    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows()
        {
            Implicit = new OpenApiOAuthFlow()
            {
                AuthorizationUrl = new Uri("https://login.microsoftonline.com/tenantId/oauth2/v2.0/authorize"),
                TokenUrl = new Uri("https://login.microsoftonline.com/tenantId/oauth2/v2.0/token"),
                Scopes = new Dictionary<string, string>
                {
                    { "api://appId/ReadAccess", "" }
                }
            }
        },
    });
    

    enter image description here

    When I clicked on Authorize option, it asked me to pick one Azure AD account and displayed below screen after successful authentication:

    enter image description here

    I got response successfully when I called the API request like this:

    GET https://localhost:xxxx/WeatherForecast
    

    enter image description here

    Reference: Enable OAuth 2 Authorization Using Azure AD And Swagger In .Net by Jay Krishna Reddy