[英]Azure Mobile Apps - Custom authentication - Unable to login
I'm working in a Xamarin Forms mobile app with .NET background. 我正在使用.NET背景的Xamarin Forms移动应用程序。 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: 在客户端获得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. 如果我使用像Google+这样的默认提供商,那就完美了。 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: 在Startup类中,我添加了:
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". 返回中的名称必须是“user”,“userId”和“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. 更正服务器代码的响应,看看是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.