gpt4 book ai didi

azure - 在 Xamarin.Forms 中使用 MSAL 获取 Azure B2C SignUpSignIn 应用程序声明

转载 作者:行者123 更新时间:2023-12-03 21:28:26 27 4
gpt4 key购买 nike

我正在使用 Azure B2C 和 MSAL(Microsoft.Identity.Client NuGet 包)创建一个 Xamarin.Forms 应用来对用户进行身份验证。当应用程序打开时,我尝试使用以下代码在后台对它们进行身份验证:

AuthenticationResult ar;
ar = await App.AuthenticationClient.AcquireTokenSilentAsync(Scopes,
userIdentifier, Authority,
SignUpSignInpolicy, false);

如果失败,应用程序会切换并使用标准 AquireTokenAsync() 方法对它们进行身份验证。

AuthenticationResult ar;
ar = await App.AuthenticationClient.AcquireTokenAsync(Config.Scopes,
"", UiOptions.SelectAccount,
string.Empty, null, Config.Authority,
Config.SignUpSignInpolicy);

我正在使用的 SignUpSignInpolicy 具有电子邮件、名字和姓氏、对象 ID 和生日(这是自定义字符串属性)的应用程序声明。

我想要做的是获取经过身份验证的用户的电子邮件、姓名和生日(如果他们必须登录),以便我可以根据该数据创建一个用户对象,该对象将在整个应用程序中使用。有没有办法从 AuthenticationResult 获取此数据?如果没有,我该如何检索 SignUpSignIn 应用程序声明?我是身份验证新手,所以我可能错过了一些重要的东西。

最佳答案

您通过 Application Claims 配置的声明 Blade 包含在 id token 中.

id token 可通过 IdToken 获得AuthenticationResult的属性(property)。 IdToken 是 Base64 编码的 JWT,您可以通过实例化 JwtSecurityToken 来访问它。类(class)。此类将允许您通过 Claims 属性访问声明。

注意:为了访问 JwtSecurityToken 类,您需要包含 System.IdentityModel.Tokens.Jwt nuget package .

以下是一些示例代码,可帮助您检索给定的声明。:

var claimName = "given_name"; // This could also be any of your custom attributes, e.g. "extension_gamertag"
authResult = await client.AcquireTokenAsync(Config.Scopes,
"", UiOptions.SelectAccount,
string.Empty, null, Config.Authority,
Config.SignUpSignInpolicy);

var jwt = new JwtSecurityToken(authResult.IdToken);
Console.WriteLine(jwt.Claims.First(c => c.Type == claimName).Value);

编辑2017-03-17由于 System.IdentityModel.Tokens.Jwt 不适用于 Xamarin/PCL,因此您可以使用 Newtonsoft.Json nuget 包自行处理 token (使用 Newtonsoft.Json.Linq);

var jwtPayloadEnc = authResult.IdToken.Split('.')[1];
var jwtPayload = Encoding.UTF8.GetString(System.Convert.FromBase64String(jwtPayloadEnc));

var payload = JObject.Parse(jwtPayload);

Console.WriteLine(payload[claimName].ToString());

编辑 2021-12-07 (以及后来的大流行)根据下面 Olias 的评论,对于 Xamarin,您可以使用:

var jwt = new JwtSecurityToken(authResult.IdToken);

关于azure - 在 Xamarin.Forms 中使用 MSAL 获取 Azure B2C SignUpSignIn 应用程序声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773234/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com