5

我正在使用 Azure B2C 和 MSAL(Microsoft.Identity.ClientNuGet 包)创建一个 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应用程序声明?我是身份验证的新手,所以我可能遗漏了一些重要的东西。

4

2 回答 2

7

您通过Application Claims刀片配置的声明包含在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 (以及后来的大流行) Per Olias 在下面的评论,对于 Xamarin,您可以使用:

var jwt = new JwtSecurityToken(authResult.IdToken);
于 2017-03-16T05:43:58.947 回答
0

您需要确保设置从您的策略返回的应用程序声明与您对客户端应用程序的期望一致。您需要为每个策略执行此操作。然后,声明将出现在作为 AuthenticationResult 的一部分传回的令牌中。示例代码包括您如何从令牌中读取声明。

于 2017-03-15T00:35:18.553 回答