Swashbuckle.aspnetcore: OAuth2 Using Azure Active Directory

Created on 7 Mar 2017  路  12Comments  路  Source: domaindrivendev/Swashbuckle.AspNetCore

I've setup the following Swagger config as shown:

var scheme = new OAuth2Scheme()
{
    AuthorizationUrl = "https://login.microsoftonline.com/{My Tenant ID}/oauth2/authorize",
    Description = "Azure Active Directory",
    Flow = "implicit",
    Scopes = new Dictionary<string, string>()
    {
        { "read", "Read Permissions " },
        { "write", "Read permissions" }
    },
    TokenUrl = "https://login.microsoftonline.com/{My Tenant ID}/oauth2/token",
    Type = "oauth2"
};
options.AddSecurityDefinition("oauth2", scheme);
// SecurityRequirementsOperationFilter copied from docs in ReadMe.md.
options.OperationFilter<SecurityRequirementsOperationFilter>();
app.UseSwaggerUi(
    options =>
    {
        options.ConfigureOAuth2(
            "2db8851d-d3e0-4a69-a575-2122277e7d14", // Client ID
            null,                                   // Client Secret
            "2db8851d-d3e0-4a69-a575-2122277e7d14", // Realm
            "My App Name");                         // App Name
    });

In my index.html file, I have also updated:

initOAuth({
  clientId: "2db8851d-d3e0-4a69-a575-2122277e7d14",
  //clientSecret: "your-client-secret-if-required",           // Don't have one
  realm: "2db8851d-d3e0-4a69-a575-2122277e7d14", // Same as Client ID?
  appName: "your-app-name",
  scopeSeparator: " ",
  additionalQueryStringParams: {}
}

I believe, that we should be using the implicit flow. I'm not sure what a Realm is, I don't think I need it according to the Azure Active Directory Docs. I can't get it working no matter what combination of properties I try. Using the implicit flow builds the following URL:

"https://login.microsoftonline.com/{My Tenant ID}/oauth2/authorize?
response_type=token
&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fswagger%2Fo2c.html
&realm=2db8851d-d3e0-4a69-a575-2122277e7d14
&client_id=2db8851d-d3e0-4a69-a575-2122277e7d14
&scope=readdevice
&state=oauth2"

This returns an invalid_resource error from Azure Active Directory which means:

The target resource is invalid because it does not exist, Azure AD cannot find it, or it is not correctly configured. This indicates the resource, if it exists, has not been configured in the tenant. The application can prompt the user with instruction for installing the application and adding it to Azure AD.

Most helpful comment

namespace Swashbuckle.AspNetCore.Swagger, class OAuth2Scheme
is missing way/parameter to provide "resource" if using Azure Active Directory, and therefore is not possible to authenticate.

Ref: https://docs.microsoft.com/en-gb/azure/active-directory/develop/active-directory-protocols-oauth-code

All 12 comments

Setting the values in the initOAuth JavaScript function fixed the problem:

initOAuth({
  clientId: "2db8851d-d3e0-4a69-a575-2122277e7d14",
  //clientSecret: "your-client-secret-if-required",
  realm: "",
  appName: "",
  scopeSeparator: " ",
  additionalQueryStringParams: {
    resource: "2db8851d-d3e0-4a69-a575-2122277e7d14"
  }
});

However, I don't know why I have to duplicate the settings like this.

I also had to add this code:

window.swaggerUiAuth = window.swaggerUiAuth || {};
window.swaggerUiAuth.tokenName = 'id_token';
if (!window.isOpenReplaced) {
    window.open = function (open) {
        return function (url) {
            url = url.replace('response_type=token', 'response_type=id_token');
            console.log(url);
            return open.call(window, url);
        };
    }(window.open);
    window.isOpenReplaced = true;

He @RehanSaeed - where and how did you integrated this code?

@robertmuehsig I was doing this for work. It's in a private Bitbucket repo unfortunately.

I figured it out - maybe its the most stupid way, but would actually work:

Copy the whole index.html from swagger under wwwroot/swagger, make sure app.UseDefaultFiles() is in the ASP.NET Core Pipeline registred and put this script before .

I also needed to integrate the nounce like that:

 if (!window.isOpenReplaced) {
     window.open = function (open) {
         return function (url) {
             url = url.replace('response_type=token', 'response_type=id_token');

             var nonce = Math.random();
             url += '&nonce=' + encodeURIComponent(nonce);

             console.log(url);

             return open.call(window, url);
         };
     }(window.open);
     window.isOpenReplaced = true;
 }

After that I received the id_token - but then I discovered that I actually want the access token for my webapi, so I removed the whole part again ;)

Hope this will help anybody in the future 馃憤

does anybody have a working example of this?

Any update on this?

namespace Swashbuckle.AspNetCore.Swagger, class OAuth2Scheme
is missing way/parameter to provide "resource" if using Azure Active Directory, and therefore is not possible to authenticate.

Ref: https://docs.microsoft.com/en-gb/azure/active-directory/develop/active-directory-protocols-oauth-code

@chigivigi You need to add the extra parameter in the UseSwaggerUI setup:

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.ConfigureOAuth2("swaggerclientid", string.Empty, string.Empty, string.Empty, additionalQueryStringParameters: new Dictionary<string, string>
    {
        { "resource", "app id url here of the resource you want to target" }
    });

    c.SwaggerEndpoint("/swagger/v1/swagger.json", "api name");
});

I am using 3rd party swagger ui - https://editor.swagger.io/ and I do not host swagger ui in my app.

@funkycoding Any info on this? I also want to use swagger, without hosting swagger-ui , with OAuth2 and resource parameter which is mandatory for Azure Active Directory Apps ...

I can't seem to get it to work without using the client ID as the resource. Is there anyway to get it to work with the app id url? I get a invalid_request.

In this case, i'm trying to log into myself. From the following link, it seems that there is issue when you try to sign in as yourself. However, this is outdated and not sure how to apply the fix since apppermission does not exist in the manifest anymore.
https://stackoverflow.com/questions/25212950/stuck-between-two-errors-in-an-azure-oauth2-token-request

Was this page helpful?
0 / 5 - 0 ratings