使用Azure AD的ASP.NET Core MVC验证ASP.NET Core WebAPI

时间:2018-05-31 13:29:29

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

我有两个Web应用程序:一个 ASP.NET Core MVC网站和一个 ASP.NET Core Web API (使用ASP.NET Core 2.1)。

我使用Azure AD对网站中的用户进行身份验证。当我将access_token从网站传递给API时(使用授权标题使用" Bearer access_token");我有这个错误:

  

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException:   IDX10503:签名验证失败。钥匙尝试:   ' Microsoft.IdentityModel.Tokens.X509SecurityKey,KeyId:...'。

我不明白为什么。

以下是本网站的配置:

services.AddAuthentication(o =>
{
    o.DefaultChallengeScheme = "aad";
    o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
{
    o.Authority = azureAdsettings.Authority;
    o.Audience = azureAdsettings.ClientId;
})
.AddCookie()
.AddOpenIdConnect("aad", o =>
{
    o.Authority = azureAdsettings.Authority;
    o.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet;
    o.ClientId = azureAdsettings.ClientId;
    o.ClientSecret = azureAdsettings.ClientSecret;
    o.ResponseType = OpenIdConnectResponseType.CodeIdToken;
    o.SaveTokens = true;
    o.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = azureAdsettings.Authority
    };
    o.Events = new OpenIdConnectEvents
    {
        OnTicketReceived = ctx =>
        {
            return Task.CompletedTask;
        },
        OnAuthorizationCodeReceived = async ctx =>
        {
            TokenProvider tokenProvider = (TokenProvider)ctx.HttpContext.RequestServices.GetRequiredService<ITokenProvider>();
            await tokenProvider.AcquireTokenByAuthorizationCodeAsync(ctx);
        },
        OnAuthenticationFailed = context =>
        {
            context.Response.Redirect("/Error");
            context.HandleResponse(); // Suppress the exception
            return Task.CompletedTask;
        },
    };
});

以下是API的配置:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.Authority = this.Configuration["AzureAd:Authority"];
    options.Audience = this.Configuration["AzureAd:ClientId"];
    options.TokenValidationParameters.ValidateIssuer = true;
    options.TokenValidationParameters.IssuerValidator = ValidateIssuer;
});

azureAdsettings 对象在appsettings.json中都是相同的。

网站上的身份验证似乎很有效。我可以获得授权码和retreive访问令牌。

0 个答案:

没有答案