如何将 AzureAD 和 AzureADBearer 添加到 asp.net core 2.2 web api

How to add AzureAD AND AzureADBearer to asp.net core 2.2 web api(如何将 AzureAD 和 AzureADBearer 添加到 asp.net core 2.2 web api)
本文介绍了如何将 AzureAD 和 AzureADBearer 添加到 asp.net core 2.2 web api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试创作一个网站,该网站使用 AzureAD 对用户进行身份验证以访问 UI 以创作数据库中的项目.而且我还希望其他服务可以通过不记名令牌调用此 API.

I'm trying to author a website that uses AzureAD to authenticate users to access UIs to author items in a DB. And I also want this API to be callable by other services via a bearer token.

services.AddAuthentication(o => {
                    o.DefaultScheme = AzureADDefaults.BearerAuthenticationScheme;
                    o.DefaultAuthenticateScheme = AzureADDefaults.AuthenticationScheme;
                })
                .AddAzureAD(options => Configuration.Bind("AzureAd", options))
                .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

我希望使用 AzureAD 方案对用户进行身份验证,但对同一 WEB API(在差异路由下)的服务由承载进行身份验证.或者拥有除两者之外的所有路线.两者都有效

I want users to be authenticated using the AzureAD scheme, but services to the same WEB API (under a dif route) to be authenticated by the bearer. Or have all routes except both. Either works

推荐答案

最终通过创建一个策略方案来解决这个问题,该方案根据存在的 auth 标头在两个模式之间切换:

ended up solving this by creating a policy scheme which toggles between the two schemas depending on the auth header present:

// add azure ad user and service authentication
            services
                .AddAuthentication("Azures")
                .AddPolicyScheme("Azures", "Authorize AzureAd or AzureAdBearer", options =>
                {
                    options.ForwardDefaultSelector = context =>
                    {
                        var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
                        if (authHeader?.StartsWith("Bearer") == true)
                        {
                            return AzureADDefaults.JwtBearerAuthenticationScheme;
                        }

                        return AzureADDefaults.AuthenticationScheme;
                    };
                })
                .AddAzureADBearer(options => config.Bind("AzureAdBearer", options))
                .AddAzureAD(options => config.Bind("AzureAd", options));

这篇关于如何将 AzureAD 和 AzureADBearer 添加到 asp.net core 2.2 web api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)