0

我正在使用带有 C# 后端的 Xamarin.Forms 重写我们的应用程序,并且我正在尝试在登录时使用 customauth。我已经让它工作到一定程度,但我正在努力将我想要从后端传递回 Xamarin 应用程序的一切。我正在获取令牌和用户 ID,但想要更多。

成功登录的后端代码似乎相对简单:

return Ok(GetLoginResult(body));

其中 GetLoginResult() 是:

private object GetLoginResult(IUser body)
        {
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, body.username)
            };

            JwtSecurityToken token = AppServiceLoginHandler.CreateToken(
                claims, signingKey, audience, issuer, TimeSpan.FromDays(30));

            accounts account = db.accounts.Single(u => u.username.Equals(body.username));

            return new LoginResult(account)
            {
                authenticationToken = token.RawData,
            };
        }

LoginResult 类是

public class LoginResult
{

    public LoginResult(accounts account)
    {
        Response = 200;
        CustomerId = account.CustomerId;
        Modules = account.Modules;
        User = new LoginResultUser
        {
            userId = account.id,
            UserName = account.UserName,
            EmployeeId = account.EmployeeId
        };
    }

    [JsonProperty(PropertyName = "Response")]
    public int Response { get; set; }

ETC

在应用程序中,我调用 customauth 如下:

MobileServiceUser azureUser = await _client.LoginAsync("custom", JObject.FromObject(account));

结果具有令牌和正确的用户 ID,但是如何使用后端传回的其他属性填充结果?我已经让后端工作并使用邮递员进行了测试,我得到的结果是我想要的,但我一直无法找到如何在应用程序中对其进行反序列化。

4

1 回答 1

0

据我所知,对于自定义 auth ,MobileServiceClient.LoginAsync将调用https://{your-app-name}.azurewebsites.net/.auth/login/custom. 使用ILSPy时,您会发现此方法只会从响应中检索user.userIdand来构造您的. 据我了解,您可以在用户成功登录后利用来检索其他用户信息。此外,您可以尝试按照此教程了解其他可能的方法。authenticationTokenCurrentUserMobileServiceClientMobileServiceClient.InvokeApiAsync

更新

您可以使用InvokeApiAsync而不是LoginAsync直接调用自定义登录端点,然后检索响应并获取附加参数,如下所示:

成功登录后,我添加了一个新属性userName并响应客户端如下:

在此处输入图像描述

对于客户端,我添加了一个自定义扩展方法来记录和检索附加参数,如下所示:

在此处输入图像描述

以下是代码片段,您可以参考它们:

MobileServiceLoginExtend.cs

public static class MobileServiceLoginExtend
{
    public static async Task CustomLoginAsync(this MobileServiceClient client, LoginAccount account)
    {
        var jsonResponse = await client.InvokeApiAsync("/.auth/login/custom", JObject.FromObject(account), HttpMethod.Post, null);
        //after successfully logined, construct the MobileServiceUser object with MobileServiceAuthenticationToken
        client.CurrentUser = new MobileServiceUser(jsonResponse["user"]["userId"].ToString());
        client.CurrentUser.MobileServiceAuthenticationToken = jsonResponse.Value<string>("authenticationToken");

        //retrieve custom response parameters
        string customUserName = jsonResponse["user"]["userName"].ToString();
    }
}

登录处理

MobileServiceClient client = new MobileServiceClient("https://bruce-chen-002-staging.azurewebsites.net/");
var loginAccount = new LoginAccount()
{
    username = "brucechen",
    password = "123456"
};
await client.CustomLoginAsync(loginAccount);
于 2017-03-17T10:25:39.890 回答