pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

ASP.NET Core 2.0 AzureAD 身份驗證不起作用

ASP.NET Core 2.0 AzureAD Authentication not working(ASP.NET Core 2.0 AzureAD 身份驗證不起作用)
本文介紹了ASP.NET Core 2.0 AzureAD 身份驗證不起作用的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我有一個 ASP.NET Core 2.0 應用程序設置,我想使用 AzureAd 對我公司的目錄進行身份驗證.我已經設置了類和啟動方法并使身份驗證工作正常,我遇到的問題是我正在嘗試為 OnAuthorizationCodeReceived 事件設置事件處理程序,以便我可以請求一個用戶令牌,然后用于 Microsoft 圖形調用.

I have an ASP.NET Core 2.0 application setup that I want to use AzureAd for the authentication with my company's directory. I have setup the classes and startup method and have the authentication piece working, the problem that I'm having is that I'm trying to setup and event handler to the OnAuthorizationCodeReceived event, so that I can request a user token that will then be used for Microsoft graph calls.

在我的 Startup.cs 中,我有以下代碼

In my Startup.cs I have the following code

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddAzureAd(options => Configuration.Bind("AzureAd", options))
            .AddCookie();

            services.AddMvc();

            services.AddSingleton(Configuration);
            services.AddSingleton<IGraphAuthProvider, GraphAuthProvider>();
            services.AddTransient<IGraphSDKHelper, GraphSDKHelper>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

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

然后在 AzureAdAuthenticationBuilderExtensions.cs 我有以下代碼.

Then in the AzureAdAuthenticationBuilderExtensions.cs I have the following code.

public static class AzureAdAuthenticationBuilderExtensions
{        
    public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, IConfiguration configuration)
        => builder.AddAzureAd(_ => { }, configuration);

    public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions, 
        IConfiguration configuration)
    {
        builder.Services.Configure(configureOptions);
        builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>();
        builder.AddOpenIdConnect(opts =>
        {
            opts.ResponseType = "code id_token";

            opts.ClientId = configuration["AzureAd:ClientId"];
            opts.Authority = $"{configuration["AzureAd:Instance"]}{configuration["AzureAd:TenantId"]}";
            opts.UseTokenLifetime = true;
            opts.CallbackPath = configuration["AzureAd:CallbackPath"];
            opts.ClientSecret = configuration["AzureAd:ClientSecret"];
            opts.RequireHttpsMetadata = false;

            opts.Events = new OpenIdConnectEvents
            {
                OnAuthorizationCodeReceived = async context =>
                {
                    var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);

                    var distributedCache = context.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
                    var userId = context.Principal
                        .FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")
                        .Value;
                    var cache = new AdalDistributedTokenCache(distributedCache, userId);
                    var authContext = new AuthenticationContext(context.Options.Authority, cache);
                    await authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code,
                        new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, context.Options.Resource);
                    context.HandleCodeRedemption();
                }
            };
        });
        return builder;
    }

    private class ConfigureAzureOptions: IConfigureNamedOptions<OpenIdConnectOptions>
    {
        private readonly AzureAdOptions _azureOptions;

        public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions)
        {
            if (azureOptions != null)
            {
                _azureOptions = azureOptions.Value;
            }
        }

        public void Configure(string name, OpenIdConnectOptions options)
        {
            options.ClientId = _azureOptions.ClientId;
            options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
            options.UseTokenLifetime = true;
            options.CallbackPath = _azureOptions.CallbackPath;
            options.RequireHttpsMetadata = false;
            options.ClientSecret = _azureOptions.ClientSecret;
        }

        public void Configure(OpenIdConnectOptions options)
        {
            Configure(Options.DefaultName, options);
        }
    }
}

然后調用 AddAzureAd 方法,我可以看到它遍歷該方法中的所有代碼,但是當我在 OnAuthorizationCodeReceived 方法中放置斷點時,斷點永遠不會被命中.我做了一堆閱讀,看起來我所擁有的是正確的,所以我猜我一定在這里遺漏了一些簡單的東西,但找不到問題.

Then AddAzureAd method is being called and I can see it walk through all of the code in this method, but when I put a breakpoint in the OnAuthorizationCodeReceived method that breakpoint never gets hit. I've done a bunch of reading and it looks like what I have is right, so I'm guessing that I must be missing something simple here, but can't find the problem.

已編輯我現在正在點擊 OnAuthorizationCodeReceived 事件,但現在應用程序無法繼續登錄,出現以下錯誤

Editted I'm now hitting the OnAuthorizationCodeReceived event, but now the application is failing to continue to log in getting the following error

SecurityTokenException: Unable to validate the 'id_token', no suitable ISecurityTokenValidator was found for: ''."
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+<HandleRequestAsync>d__12.MoveNext()

Stack Query Cookies Headers
SecurityTokenException: Unable to validate the 'id_token', no suitable ISecurityTokenValidator was found for: ''."
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+<HandleRequestAsync>d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

推薦答案

Asp.net core 2.0的OpenIdConnect組件使用隱式流(response_type的值為id_token).

The OpenIdConnect component for Asp.net core 2.0 uses implicit flow(the value of response_type is id_token).

要觸發 OnAuthorizationCodeReceived 事件,我們應該使用 'response_type' 參數包含 code 值的混合流.(例如.id_token 代碼).我們需要通過 OpenIdConnectOptions 設置它,如下代碼:

To fire the OnAuthorizationCodeReceived the event, we should use the hybrid flow which's 'response_type' parameter contains code value.(eg. id_token code). And we need set it through the OpenIdConnectOptions like code below:

.AddOpenIdConnect(options =>
{
    options.Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAd:Tenant"]);
    options.ClientId = Configuration["AzureAd:ClientId"];
    options.ResponseType = "code id_token";     
});

options.Events = new OpenIdConnectEvents
{
    OnAuthorizationCodeReceived = async context =>
    {
        var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);

        var authContext = new AuthenticationContext(context.Options.Authority);
        var authResult=await authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code,
            new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, context.Options.Resource);
        context.HandleCodeRedemption(authResult.AccessToken, context.ProtocolMessage.IdToken);
    },
};

這篇關于ASP.NET Core 2.0 AzureAD 身份驗證不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 進行身份驗證并跨請求保留自定義聲明)
ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用)
ASP Core Azure Active Directory Login use roles(ASP Core Azure Active Directory 登錄使用角色)
How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何獲取守護進程或服務器到 C# ASP.NET Web API 的 Azure AD OAuth2 訪問令牌和刷新令牌) - IT屋-程序員軟件開發技
.Net Core 2.0 - Get AAD access token to use with Microsoft Graph(.Net Core 2.0 - 獲取 AAD 訪問令牌以與 Microsoft Graph 一起使用)
Azure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(異步調用時 Azure KeyVault Active Directory AcquireTokenAsync 超時)
主站蜘蛛池模板: 杭州翻译公司_驾照翻译_专业人工翻译-杭州以琳翻译有限公司官网 组织研磨机-高通量组织研磨仪-实验室多样品组织研磨机-东方天净 | 机械立体车库租赁_立体停车设备出租_智能停车场厂家_春华起重 | 河南生物显微镜,全自动冰冻切片机-河南荣程联合科技有限公司 | 分光色差仪,测色仪,反透射灯箱,爱色丽分光光度仪,美能达色差仪维修_苏州欣美和仪器有限公司 | 屏蔽泵厂家,化工屏蔽泵_维修-淄博泵业 | 考勤系统_人事考勤管理系统_本地部署BS考勤系统_考勤软件_天时考勤管理专家 | 智能气瓶柜(大型气瓶储存柜)百科 | 南京展台搭建-南京展会设计-南京展览设计公司-南京展厅展示设计-南京汇雅展览工程有限公司 | 硫酸亚铁-聚合硫酸铁-除氟除磷剂-复合碳源-污水处理药剂厂家—长隆科技 | 转子泵_凸轮泵_凸轮转子泵厂家-青岛罗德通用机械设备有限公司 | 骨密度仪-骨密度测定仪-超声骨密度仪-骨龄测定仪-天津开发区圣鸿医疗器械有限公司 | 船老大板材_浙江船老大全屋定制_船老大官网 | 液压油缸-液压缸厂家价格,液压站系统-山东国立液压制造有限公司 液压油缸生产厂家-山东液压站-济南捷兴液压机电设备有限公司 | 对夹式止回阀_对夹式蝶形止回阀_对夹式软密封止回阀_超薄型止回阀_不锈钢底阀-温州上炬阀门科技有限公司 | 合肥制氮机_合肥空压机厂家_安徽真空泵-凯圣精机 | 商用绞肉机-熟肉切片机-冻肉切丁机-猪肉开条机 - 广州市正盈机械设备有限公司 | 铝箔袋,铝箔袋厂家,东莞铝箔袋,防静电铝箔袋,防静电屏蔽袋,防静电真空袋,真空袋-东莞铭晋让您的产品与众不同 | 蔬菜清洗机_环速洗菜机_异物去除清洗机_蔬菜清洗机_商用洗菜机 - 环速科技有限公司 | 安全,主动,被动,柔性,山体滑坡,sns,钢丝绳,边坡,防护网,护栏网,围栏,栏杆,栅栏,厂家 - 护栏网防护网生产厂家 | 报警器_家用防盗报警器_烟雾报警器_燃气报警器_防盗报警系统厂家-深圳市刻锐智能科技有限公司 | 电脑刺绣_绣花厂家_绣花章仔_织唛厂家-[源欣刺绣]潮牌刺绣打版定制绣花加工厂家 | 切铝机-数控切割机-型材切割机-铝型材切割机-【昆山邓氏精密机械有限公司】 | 螺钉式热电偶_便携式温度传感器_压簧式热电偶|无锡联泰仪表有限公司|首页 | 对照品_中药对照品_标准品_对照药材_「格利普」高纯中药标准品厂家-成都格利普生物科技有限公司 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库 | 厂厂乐-汇聚海量采购信息的B2B微营销平台-厂厂乐官网 | 锥形螺带干燥机(新型耙式干燥机)百科-常州丰能干燥工程 | 工业洗衣机_工业洗涤设备_上海力净工业洗衣机厂家-洗涤设备首页 bkzzy在职研究生网 - 在职研究生招生信息咨询平台 | 电竞学校_电子竞技培训学校学院-梦竞未来电竞学校官网 | 铣刨料沥青破碎机-沥青再生料设备-RAP热再生混合料破碎筛分设备 -江苏锡宝重工 | 鑫铭东办公家具一站式定制采购-深圳办公家具厂家直销 | 金属波纹补偿器厂家_不锈钢膨胀节价格_非金属伸缩节定制-庆达补偿器 | 商用绞肉机-熟肉切片机-冻肉切丁机-猪肉开条机 - 广州市正盈机械设备有限公司 | 电解抛光加工_不锈钢电解抛光_常州安谱金属制品有限公司 | 净水器代理,净水器招商,净水器加盟-FineSky德国法兹全屋净水 | 阻垢剂,反渗透阻垢剂,缓蚀阻垢剂-山东普尼奥水处理科技有限公司 真空粉体取样阀,电动楔式闸阀,电动针型阀-耐苛尔(上海)自动化仪表有限公司 | 中矗模型-深圳中矗模型设计有限公司 | 无刷电机_直流无刷电机_行星减速机-佛山市藤尺机电设备有限公司 无菌检查集菌仪,微生物限度仪器-苏州长留仪器百科 | 电子海图系统-电梯检验系统-智慧供热系统开发-商品房预售资金监管系统 | PSI渗透压仪,TPS酸度计,美国CHAI PCR仪,渗透压仪厂家_价格,微生物快速检测仪-华泰和合(北京)商贸有限公司 | 长江船运_国内海运_内贸船运_大件海运|运输_船舶运输价格_钢材船运_内河运输_风电甲板船_游艇运输_航运货代电话_上海交航船运 | 专业的新乡振动筛厂家-振动筛品质保障-环保振动筛价格—新乡市德科筛分机械有限公司 |