简体   繁体   English

AuthenticationFailed 的 Azure AD 授权错误:IDX10501:签名验证失败。 无法匹配“孩子”

[英]Azure AD Authorize Error of AuthenticationFailed: IDX10501: Signature validation failed. Unable to match 'kid'

I have 2 projects, one is for API and 2nd is for to view and get data by using 1st project's APIs.我有 2 个项目,一个用于 API,第二个用于使用第一个项目的 API 查看和获取数据。 For both I have implemented Azure AD authentication but my issue is when try to call API from 2nd project back-end(C#) with Bearer token but in response i am getting below error.对于这两者,我都实现了 Azure AD 身份验证,但我的问题是当尝试使用不记名令牌从第二个项目后端(C#)调用 API 时,但作为响应,我遇到了以下错误。

Note: I have use [Authorize] Filter in each and every class and the method in both project.注意:我在每个类和两个项目中的方法中都使用了 [Authorize] Filter。

Error错误

AuthenticationFailed: IDX10501: Signature validation failed. AuthenticationFailed: IDX10501: 签名验证失败。 Unable to match 'kid': 'SSQdhI1cKvhQEDSJxE2gGYs40Q0', token: '{"alg":"RS256","typ":"JWT","kid":"SSQdhI1cKvhQEDSJxE2gGYs40Q0"}.{"aud":"1e615ddb-ad4d-4e65-98de-c6f5db1ae08a","iss":" https://login.microsoftonline.com/5c58f0d9-2f98-4eb0-91f2-ec6afd4242f8/v2.0 ","iat":1518520450,"nbf":1518520450,"exp":1518524350,"aio":"Y2NgYHiknfZAIvPElucJpgeZzRa5AAA=","azp":"1e615ddb-ad4d-4e65-98de-c6f5db1ae08a","azpacr":"1","e_exp":262800,"oid":"159f0ec6-c5b9-4bfc-88d0-77924bd40b3f","sub":"159f0ec6-c5b9-4bfc-88d0-77924bd40b3f","tid":"5c58f0d9-2f98-4eb0-91f2-ec6afd4242f8","uti":"t8CU6YtsHE-5M9TbQm4aAA","ver":"2.0"}'.无法匹配 'kid': 'SSQdhI1cKvhQEDSJxE2gGYs40Q0', 令牌: '{"alg":"RS256","typ":"JWT","kid":"SSQdhI1cKvhQEDSJxE2gGYs40"d-e2gGYs404d"d-e2g" 4e65-98de-c6f5db1ae08a","iss":" https://login.microsoftonline.com/5c58f0d9-2f98-4eb0-91f2-ec6afd4242f8/v2.0 ","iat":1518520450,"151b8f" exp":1518524350,"aio":"Y2NgYHiknfZAIvPElucJpgeZzRa5AAA=","azp":"1e615ddb-ad4d-4e65-98de-c6f5db1ae08a","azpacr":"1","259"ec_exp:"1","259"ec_exp:" -c5b9-4bfc-88d0-77924bd40b3f","sub":"159f0ec6-c5b9-4bfc-88d0-77924bd40b3f","tid":"5c58f0d9-2f98-4eb0"tc5aaa-4eb0"tc5aaaa-c5b9-4bfc-88d0-77924bd40b3f" ","ver":"2.0"}'。

Start class ConfigureServices Method启动类 ConfigureServices 方法

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddAzureAdB2C(options =>  Configuration.Bind("Authentication:AzureAdB2C", options))           
        .AddCookie();

        // Add framework services.
        services.AddMvc();

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromHours(1);
            options.CookieHttpOnly = true;
        });
    }

Start class Configure method启动类配置方法

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseSession();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Class for to get Bearer Token获取承载令牌的类

public class ServicePrincipal
{        
    static string authority = "https://login.microsoftonline.com/{TenantID}/{Policy}/v2.0/";  
    static string clientId = "XXX"; 
    static string clientSecret = "XXX"; 
    static string resource = "XXX"; 

    static public async Task<Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> GetS2SAccessTokenForProdMSAAsync()
    {
        return await GetS2SAccessToken(authority, resource, clientId, clientSecret);
    }

    static async Task<Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> GetS2SAccessToken(string authority, string resource, string clientId, string clientSecret)
    {
        var clientCredential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret);
        AuthenticationContext context = new AuthenticationContext(authority, false);
        Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult = await context.AcquireTokenAsync(resource,clientCredential);  
        return authenticationResult;
    }
}

Controller method from where I am trying to calling 1st project's API我试图调用第一个项目的 API 的控制器方法

public async Task<IActionResult> GetCustomerGroupAsync()
    {
        try
        {

            var token = await ServicePrincipal.GetS2SAccessTokenForProdMSAAsync();                
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
            HttpResponseMessage response = await _client.GetAsync("http://localhost:49942/api/customermodule/v0.3/customergroup");
            response.EnsureSuccessStatusCode();
            string receiveStream = await response.Content.ReadAsStringAsync();
            return null;
        }
        catch (Exception e)
        {
            return Json(new { Error = e.Message });
        }
    }

Please let me know if I am missing anything or am i doing wrong?, thank you.如果我遗漏了什么或者我做错了什么,请告诉我,谢谢。

Based on your GetCustomerGroupAsync action, you are using the client credentials flow in your website backend to access the secured resource (Web API) with Azure AD B2C.根据您的GetCustomerGroupAsync操作,您正在使用网站后端中的客户端凭据流通过 Azure AD B2C 访问安全资源 (Web API)。 As Azure Active Directory B2C: Types of applications mentions under the Current limitations section as follows:作为Azure Active Directory B2C:当前限制部分提到的应用程序类型如下:

Daemons/server-side apps守护进程/服务器端应用程序

Apps that contain long-running processes or that operate without the presence of a user also need a way to access secured resources such as web APIs.包含长时间运行的进程或在用户不在场的情况下运行的应用程序也需要一种访问安全资源(例如 Web API)的方法。 These apps can authenticate and get tokens by using the app's identity (rather than a user's delegated identity) and by using the OAuth 2.0 client credentials flow.这些应用程序可以使用应用程序的身份(而不是用户的委派身份)和 OAuth 2.0 客户端凭据流进行身份验证并获取令牌。

This flow is not currently supported by Azure AD B2C. Azure AD B2C 当前不支持此流。 These apps can get tokens only after an interactive user flow has occurred.这些应用程序只有在交互式用户流发生后才能获得令牌。

Moreover, you could follow the git samples below to implement your requirement:此外,您可以按照下面的 git 示例来实现您的要求:

An ASP.NET Core 2.0 web API with Azure AD B2C 带有 Azure AD B2C 的 ASP.NET Core 2.0 Web API

An ASP.NET Core web app with Azure AD B2C 带有 Azure AD B2C 的 ASP.NET Core Web 应用

Because you need to retrive access token, it must be a call to OAuth endpoint.因为您需要检索访问令牌,所以它必须是对 OAuth 端点的调用。 Try with the below one to get Azure AD access token尝试使用以下方法获取 Azure AD 访问令牌

https://login.microsoftonline.com/{TenantID}/oauth2/token

More over, just need to make sure the authorization header is constructed in valid format: Bearer更重要的是,只需要确保以有效格式构造授权头:Bearer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure b2c 错误:IDX10501:签名验证失败。 无法匹配密钥:孩子:&#39;gLv****************&#39; - Azure b2c error: IDX10501: Signature validation failed. Unable to match key: kid: 'gLv****************' IDX10501:签名验证失败。 无法匹配键 - IDX10501: Signature validation failed. Unable to match keys IDX10501:签名验证失败。小孩:'[PII隐藏]',令牌:'[PII隐藏]' - Azure B2C - IDX10501: Signature validation failed. kid: '[PII is hidden]', token: '[PII is hidden]' - Azure B2C Azure AD B2C 错误 - IDX10501:签名验证失败 - Azure AD B2C error - IDX10501: Signature validation failed IDX10500:签名验证失败。 无法解析 SecurityKeyIdentifier - IDX10500: Signature validation failed. Unable to resolve SecurityKeyIdentifier 每隔一个请求 JWT 验证失败,'idx10503 签名验证失败。 令牌没有孩子' - Every other request JWT validation fails with 'idx10503 signature validation failed. token does not have a kid' IDX10503:签名验证失败。 令牌没有孩子。 键尝试:'System.Text.StringBuilder' - IDX10503: Signature validation failed. Token does not have a kid. Keys tried: 'System.Text.StringBuilder' Asp.NET 核心 3 - Azure Active Directory - 令牌验证失败 - 签名验证失败。 无法匹配密钥 - Asp.NET Core 3 - Azure Active Directory - Token Validation fails - Signature validation failed. Unable to match key 抛出“IDX10223:生命周期验证失败。 令牌已过期。” 使用 Microsoft.Owin.Security.OpenIdConnect 使用 Azure AD 时 - Throw “IDX10223: Lifetime validation failed. The token is expired.” when working Azure AD with Microsoft.Owin.Security.OpenIdConnect IDX10500:签名验证失败。 没有提供安全密钥来验证签名 - IDX10500: Signature validation failed. No security keys were provided to validate the signature
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM