![](/img/trans.png)
[英]How to Integrate existing Azure AD B2C into a Xamarin forms app using MSAL?
[英]Getting Azure B2C SignUpSignIn Application Claims using MSAL in Xamarin.Forms
我正在创建一个 Xamarin.Forms 应用程序,使用 Azure B2C 和 MSAL( Microsoft.Identity.Client
NuGet 包)对用户进行身份验证。 当应用程序打开时,我尝试使用以下代码在后台对它们进行身份验证:
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
应用程序声明? 我是身份验证的新手,所以我可能遗漏了一些重要的东西。
您通过应用程序声明刀片配置的声明包含在id token 中。
id 令牌可通过AuthenticationResult的IdToken属性获得。 IdToken 是 Base64 编码的 JWT,您可以通过实例化JwtSecurityToken类来访问它。 此类将使您可以通过 Claims 属性访问声明。
注意:为了访问 JwtSecurityToken 类,您需要包含System.IdentityModel.Tokens.Jwt nuget 包。
下面是一些示例代码,可帮助您检索给定的声明。:
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 包(使用 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.