Azure移动应用程序-自定义身份验证-无法登录 [英] Azure Mobile Apps - Custom authentication - Unable to login

查看:82
本文介绍了Azure移动应用程序-自定义身份验证-无法登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.NET背景的Xamarin Forms移动应用程序.我尽可能地遵循了指南.但是这些以某种方式还没有完成,并且没有完整的自定义身份验证示例.我终于达到了我现在不该如何前进的地步.我无法使登录正常工作.

I'm working in a Xamarin Forms mobile app with .NET background. I followed the guides as much as I could. But those are somehow uncompleted and there are not complete examples of custom authentication. I finally reach a point were I don't now how to advance. I can't make the login work.

客户端收到LoginAsync的响应后,我得到此错误:

I get this error after the client gets the respond of the LoginAsync:

     user = await TodoItemManager.DefaultManager.CurrentClient.LoginAsync("CustomAuth", credentials);

这是错误:

ex {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}

如果我使用像Google+这样的默认提供程序,那就完美了.所以我认为问题出在后端.但是我不知道我在做什么错.我循环了几次代码,看起来还不错. 我尝试调试服务器端,直到到达客户端为止,我没有收到任何错误.

If I use a default provider like Google+ works perfect. So I think the problem is in the backend. But I don't know what I'm doing wrong. I loop up the code several times and looks fine. I tried debugging the server side and I didn't get any error until it reaches the client side.

我在做什么错了?

这是我在服务器端的代码.

This is my code in the server side.

    public IHttpActionResult Post(LoginRequest loginRequest)
    {
        if (isValidAssertion(loginRequest.username, loginRequest.password)) // user-defined function, checks against a database
        {
            JwtSecurityToken token = GetAuthenticationTokenForUser(loginRequest.username);

            return Ok(new
            {
                AuthenticationToken = token.RawData,
                User = new { UserId = loginRequest.username }
            });
        }
        else // user assertion was not valid
        {
            return Unauthorized();
        }
    }

辅助功能:

    private bool isValidAssertion(string username, string password)
    {
        AspNetUsers AspNetUser = db.AspNetUsers.SingleOrDefault(x => x.UserName.ToLower() == username.ToLower());
        return AspNetUser != null && VerifyHashedPassword(AspNetUser.PasswordHash, password);
    }

    private JwtSecurityToken GetAuthenticationTokenForUser(string username)
    {
        var claims = new Claim[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, username)
        };

        string signingKey = "123456789123456789...";//Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
        string audience = "https://todo.azurewebsites.net/"; // audience must match the url of the site
        string issuer = "https://todo.azurewebsites.net/"; // audience must match the url of the site

        JwtSecurityToken token = AppServiceLoginHandler.CreateToken(
            claims,
            signingKey,
            audience,
            issuer,
            TimeSpan.FromHours(24)
        );

        return token;
    }

在启动类中,我添加了:

In the Startup class I added:

        config.Routes.MapHttpRoute("CustomAuth", ".auth/login/CustomAuth", new { controller = "CustomAuth" });

这是我在客户端的代码:

And this is my code in the client side:

    public async Task<bool> Authenticate()
    {
        string username = "todo@gmail.com";
        string password = "todo";

        string message = string.Empty;
        var success = false;
        var credentials = new JObject
        {
            ["username"] = username,
            ["password"] = password
        };
        try
        {
            user = await TodoItemManager.DefaultManager.CurrentClient.LoginAsync("CustomAuth", credentials);
            if (user != null)
            {
                success = true;
                message = string.Format("You are now signed-in as {0}.", user.UserId);
            }
        }
        catch (Exception ex)
        {
            message = string.Format("Authentication Failed: {0}", ex.Message);
        }
        await new MessageDialog(message, "Sign-in result").ShowAsync();
        return success;
    }

感谢您的帮助.

编辑(解决方案):

我要为遇到同样问题的人澄清.该错误大约是一些大写/小写的差异.返回中的名称必须为"user","userId"和"authenticationToken".完全像这样:

I'm gonna clarify for people with the same problem. The error was about some uppercase/lowercase differences. The names in the return must be "user", "userId" and "authenticationToken". Exactly like this:

        return Ok(new
        {
            authenticationToken = token.RawData,
            user = new { userId = loginRequest.username }
        });

推荐答案

您的服务器响应似乎不正确.查看有效的响应,看起来它应该是:

It looks like your response from the server is wrong. Looking at a valid response, it looks like it needs to be:

{
    "user": "your-user-id",
    "authenticationToken": "the-jwt"
}

更正服务器代码中的响应,看看是否有帮助.

Correct the response from your server code and see if that helps.

这篇关于Azure移动应用程序-自定义身份验证-无法登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆