简体   繁体   中英

Azure Mobile Apps - Custom authentication - Unable to login

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.

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

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

This is the error :

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

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.

What Am I doing wrong?

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();
        }
    }

The auxiliar functions:

    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;
    }

Thanks for the help.

EDIT (Solution):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM