使用msal.net获取Azure B2C用户目录列表

发布于 2025-01-23 01:23:58 字数 1154 浏览 0 评论 0原文

当前,我们使用MS Graph和DirectoryObjects/GetByids端点获得了用户列表。

在ASP Net Core API的启动中,我们正在使用Microsoft.InderityModel.Clients.ActiveDirectory,并且此代码

services.AddHttpClient("GraphApi", async hc =>
{
    AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + this.configuration["GraphApi:Tenant"]);
    ClientCredential credential = new ClientCredential(this.configuration["GraphApi:ClientId"], this.configuration["GraphApi:ClientSecret"]);
    hc.BaseAddress = new Uri($"https://graph.microsoft.com/v1.0/");
    hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credential);
    hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
});

我正在创建一个新的Azure函数,并且需要再次做同样的事情。我将使用相同的代码和Microsoft.IdentityModel.Clients.ClivesiveDirectory,但是该软件包已被弃用,我们应该使用Microsoft.Identity.Client。

我可以看到许多针对各种情况的样本,但它们似乎都在调用公共MS图,而我想从我们自己的Azure B2C中获得用户。有人可以将我指向正确的资源\演示吗?

Azure函数不会在用户的上下文中运行

We are currently getting a list of our Users using MS Graph and the directoryObjects/getByIds endpoint.

In the Startup of the ASP NET Core API we are using Microsoft.IdentityModel.Clients.ActiveDirectory and this code

services.AddHttpClient("GraphApi", async hc =>
{
    AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + this.configuration["GraphApi:Tenant"]);
    ClientCredential credential = new ClientCredential(this.configuration["GraphApi:ClientId"], this.configuration["GraphApi:ClientSecret"]);
    hc.BaseAddress = new Uri(
quot;https://graph.microsoft.com/v1.0/");
    hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credential);
    hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
});

I am creating a new Azure Function and need to do the same thing again. I was going to use the same code and Microsoft.IdentityModel.Clients.ActiveDirectory but that package has been deprecated and we should be using Microsoft.Identity.Client.

I can see lots of samples for various scenarios but they seem to be all calling the public MS Graph whereas I want to get the users from our own Azure B2C. Can someone point me at the right resources\demo.

The Azure Function will not be running in the context of a user so Managed Identity or Client Secret approach would be useful

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖 2025-01-30 01:23:58

我已经实现了一种类似的方案来获取Azure AD用户,但是MVC

代码

中的不同方式我使用了这些Nuget软件包

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;

启动类

public class Startup
    {
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

        string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

        static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    RedirectUri = redirectUri,
                    PostLogoutRedirectUri = redirectUri,
                    Scope = OpenIdConnectScope.OpenIdProfile,
                    ResponseType = OpenIdConnectResponseType.CodeIdToken,
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = false // This is a simplification
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed
                    },
                }
            );
        }

        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }

Homecontroller

public void SignIn()
        {
            if (!Request.IsAuthenticated)
            {

                HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }

        public void SignOut()
        {
            HttpContext.GetOwinContext().Authentication.SignOut( OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
        }

SopeconTroller

public ActionResult Index()
        {
            var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;

            ViewBag.Name = userClaims?.FindFirst("name")?.Value;
            ViewBag.Username = userClaims?.FindFirst("preferred_username")?.Value;
            ViewBag.Subject = userClaims?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
            ViewBag.TenantId = userClaims?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
            return View();
        }

,我试图涵盖所有可能的实现。 的情况下它会起作用

希望在您

I have implemented a similar kind of scenario for getting Azure AD user but different way in MVC

CODE

I have used these NuGet packages

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;

Startup class

public class Startup
    {
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

        string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

        static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    RedirectUri = redirectUri,
                    PostLogoutRedirectUri = redirectUri,
                    Scope = OpenIdConnectScope.OpenIdProfile,
                    ResponseType = OpenIdConnectResponseType.CodeIdToken,
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = false // This is a simplification
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed
                    },
                }
            );
        }

        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }

HomeController

public void SignIn()
        {
            if (!Request.IsAuthenticated)
            {

                HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }

        public void SignOut()
        {
            HttpContext.GetOwinContext().Authentication.SignOut( OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
        }

ClaimsController

public ActionResult Index()
        {
            var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;

            ViewBag.Name = userClaims?.FindFirst("name")?.Value;
            ViewBag.Username = userClaims?.FindFirst("preferred_username")?.Value;
            ViewBag.Subject = userClaims?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
            ViewBag.TenantId = userClaims?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
            return View();
        }

I tried to cover all possible implementations. Hope it will work in your case

Thanks

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文