I'm developing my first Xamarin cross-platform application for Android and iOS (using Xamarin Forms). The application will require the user to login using a REST API and stay authenticated.
I want to use the token from my API, which is JWT, on my Xamarin application for the user to login
I don't know how to do this and all I have seen is with OAuth authentication.
Here is how I generate the token on my API project
private string GenerateToken(CrUserInfo user)
{
//Header
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]));
var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
var header = new JwtHeader(signingCredentials);
//Claims
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Username),
new Claim("User", user.Displayname),
new Claim(ClaimTypes.Role, user.Role.ToString()),
};
//Payload
var payload = new JwtPayload
(
_configuration["Authentication:Issuer"],
_configuration["Authentication:Audience"],
claims,
DateTime.Now,
DateTime.Now.AddMinutes(300)
);
var token = new JwtSecurityToken(header, payload);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Here is my post method which returns the Token
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(string))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.Unauthorized)]
public async Task<IActionResult> Authentication(UserLogin login)
{
//if it is a valid user
var validation = await IsValidUser(login);
if (validation.Item1)
{
if(validation.Item2 != null)
{
var token = GenerateToken(validation.Item2);
return Ok(new { token });
}
}
return NotFound("Unvalid User");
}
And I'm now trying to login a user on my Xamarin project but, as I said, all I see is OAuth authentication. The closest question I've seen was this one Xamarin.Forms how to access the current logged in user's Id and other information? - Stack Overflow but I don't know how to implement it.