如何在.NET Core 2.2 WebApi和Azure AD 2.0中配置Swagger?

时间:2019-05-01 18:15:48

标签: c# asp.net-core .net-core azure-active-directory asp.net-core-webapi

我对Swagger的“授权”功能有疑问,该功能用于使用Azure AD 2.0终结点对WebApi应用程序进行身份验证。我在启动类中使用了以下设置,但获取的令牌无法验证Swagger内部的承载令牌。该API可与react客户端发送的令牌配合使用。

private const string AzureAdConfigKey = "AzureAd";
private const string OAuth2Definition = "openid";

private IConfiguration Configuration { get; }
private IHostingEnvironment Environment { get; }

public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
    Environment = environment;
    Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
        .AddAzureADBearer(options => Configuration.Bind(AzureAdConfigKey, options));

    services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme,
        options => options.Authority += "/v2.0");

    var authorizationPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();

    services.AddMvc(options => options.Filters.Add(new AuthorizeFilter(authorizationPolicy)))
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    var azureAdAuthority = $"https://login.microsoftonline.com/{Configuration["AzureAd:TenantId"]}/oauth2/v2.0";
    services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new Info
        {
            Title = "My Api Name",
            Version = "v1"
        });

        options.AddSecurityDefinition(OAuth2Definition, new OAuth2Scheme
        {
            Description = "OAuth2 Implicit Grant",
            Flow = "implicit",
            AuthorizationUrl = $"{azureAdAuthority}/authorize",
            TokenUrl = $"{azureAdAuthority}/connect/token",
            Scopes = new Dictionary<string, string>
            {
                {OAuth2Definition, "User.Read"}
            }
        });

        options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {{OAuth2Definition, null}});
    });

    services.AddCors(options => options.AddPolicy("AllowSpecificOrigin", builder => builder
        .WithOrigins(Configuration["MyAppClientUrl"])
        .AllowCredentials()
        .AllowAnyHeader()
        .AllowAnyMethod()
    ));

    // Other Service Registrations.
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware<ErrorHandlingMiddleware>();

    app.UseCors("AllowSpecificOrigin");

    app.UseHsts();
    app.UseHttpsRedirection();

    app.UseSwagger();
    app.UseSwaggerUI(config =>
    {
        const string swaggerName = "MyApp Coding Api";
        const string swaggerUrl = "/swagger/v1/swagger.json";

        config.SwaggerEndpoint(swaggerUrl, swaggerName);
        config.RoutePrefix = string.Empty;

        config.OAuthAppName(swaggerName);
        config.OAuthClientId(Configuration["AzureAd:ClientId"]);
        config.OAuthClientSecret(Configuration["AzureAd:ClientSecret"]);
        // This is my Api local path.
        config.OAuthRealm("https://localhost:44398/swagger/ui/o2c-html");
        config.OAuthScopeSeparator(" ");
    });

    app.UseAuthentication();
    app.UseMvc();
}

以下是客户端生成的令牌,该令牌可以正常工作并实现.v2.0:

{
  "aud": "{Excldued}",
  "iss": "https://login.microsoftonline.com/{Excldued}/v2.0",
  "iat": 1556730915,
  "nbf": 1556730915,
  "exp": 1556734815,
  "aio": "AVQAq/8LAAAA9lULrpdFyoAfnaWTCkdo8PMz2vL4C0MbDNAxmRBa3rMETsjpnXYFb5izdF/VRWMLzOvwgmw9Zt3zzisWRbLCFMd5KAaJ59wUDqNdSoawS6U=",
  "name": "{Excldued}",
  "nonce": "{Excldued}",
  "oid": "{Excldued}",
  "preferred_username": "{Excldued}",
  "roles": [
    "Coder",
    "Supervisor"
  ],
  "sub": "Jn0w0rhsGpwTKPdSjQBLHeHDv2_TD4kaOjo0x06JWKQ",
  "tid": "{Excldued}",
  "uti": "pOW4Q_EBdkSv_q0-OHRSAA",
  "ver": "2.0"
}

但是大张旗鼓会生成以下令牌,即.v1.0:

{
  "aud": "00000003-0000-0000-c000-000000000000",
  "iss": "https://sts.windows.net/{Excluded}/",
  "iat": 1556733552,
  "nbf": 1556733552,
  "exp": 1556737452,
  "acct": 0,
  "acr": "1",
  "aio": "AUQAu/8LAAAA9YXDyeK8KuCHbNgw7RGU8GgJk3qpWB1H+Q3i/dC/VRoAtYvp3NHFIYcTFxn3jfTPvvXRWx5MN35kvO0iCK7ftg==",
  "amr": [
    "pwd",
    "mfa"
  ],
  "app_displayname": "{Excluded}",
  "appid": "{Excluded}",
  "appidacr": "0",
  "family_name": "{Excluded}",
  "given_name": "{Excluded}",
  "ipaddr": "{Excluded}",
  "name": "{Excluded}",
  "oid": "{Excluded}",
  "onprem_sid": "{Excluded}",
  "platf": "3",
  "puid": "{Excluded}",
  "scp": "openid profile User.Read email",
  "signin_state": [
    "kmsi"
  ],
  "sub": "{Excluded}",
  "tid": "{Excluded}",
  "unique_name": "{Excluded}",
  "upn": "{Excluded}",
  "uti": "{Excluded}",
  "ver": "1.0",
  "xms_st": {
    "sub": "{Excluded}"
  },
  "xms_tcdt": 1361394419
}

在请求1.0终结点并获得错误令牌类型的Swagger配置中我做错了什么?

更新:

这是对Azure AD授权终结点的提琴手请求:

GET https://login.microsoftonline.com/{TenantId}/oauth2/v2.0/authorize?response_type=token&client_id={ClientId}&redirect_uri=https%3A%2F%2Flocalhost%3A44350%2Foauth2-redirect.html&scope=openid&state={StateValue}&nonce=123456 HTTP/1.1
Host: login.microsoftonline.com
Connection: keep-alive
Upgrade-Insecure-Requests: 1
DNT: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Referer: https://localhost:44350/index.html
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

1 个答案:

答案 0 :(得分:0)

获得v1.0令牌的原因是因为您试图访问v1.0资源。请在此处查看文章:https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens

  

访问令牌是根据令牌的受众创建的,这意味着拥有令牌范围的应用程序。这就是将应用清单中的资源设置accessTokenAcceptedVersion设置为2的方式,从而允许调用v1.0终结点的客户端接收v2.0访问令牌。同样,这就是为什么更改客户端的访问令牌可选声明不会更改为user.read请求令牌时收到的访问令牌的原因,该令牌由MS Graph资源拥有。   出于相同的原因,在使用个人帐户(例如hotmail.com或Outlook.com)测试客户端应用程序时,您可能会发现客户端收到的访问令牌是不透明的字符串。这是因为正在访问的资源已经请求了旧版MSA(Microsoft帐户)票证,这些票证已加密并且客户端无法理解。

您的v1.0令牌具有由v1.0端点发布的Microsoft Graph的受众。如果您在此处关注文章:https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow 您将看到,即使到达v2.0终结点,并向Postman请求资源graph.microsoft.com的访问令牌,您也将获得iss​​没有v2.0的访问令牌。

这也是非常有用的资源,因为它很好地引用了Azure中一些流行的GUID。 :https://www.shawntabrizi.com/aad/common-microsoft-resources-azure-active-directory/