I am converting dontcore web API on a new development stack to go serverless using the Azure functions.
I am thinking that my application should use Identity to store user credentials and other details. and he should get authenticated across Identity DataBase and generated using JWT tokens.
I am trying to get hold of some examples that might be helpful to see how to implement JWT in Azure functions.
JWT Token Generation Process
public UserResponce AuthendicateUser(string username, string password)
{
bool valid_user= ValidateUser(username,password);
if (vlaid_user)
{
// authentication successful so generate jwt token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtIssuerOptions.Value.JwtKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "1"),
new Claim(ClaimTypes.GivenName, username),
new Claim(ClaimTypes.Role, UserRoleEnum.superadmin.ToString()),
new Claim("hospitalid", "1")
}),
Expires = DateTime.UtcNow.AddMinutes(_jwtIssuerOptions.Value.JwtExpireMinutes),
IssuedAt = DateTime.UtcNow,
NotBefore = DateTime.UtcNow,
Audience = _jwtIssuerOptions.Value.JwtAuidence,
Issuer = _jwtIssuerOptions.Value.JwtIssuer,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
string newJwttoken = tokenHandler.WriteToken(token);
return new UserResponce
{
//HospitalId = user.HospitalId.Value,
Token = newJwttoken,
UserId = 1,
UserName = username,
Expires = DateTime.UtcNow.AddMinutes(_jwtIssuerOptions.Value.JwtExpireMinutes),
};
}
else
{
return null;
}
}
Using Functions like Bellow code, where user, identity values getting Nulls
var user = req.HttpContext.User;
var identity = claimsPrincipal.Identity;
Function Code
[FunctionName("Get_User")]
public async Task<IActionResult> GetUser(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = Globals.UserRoute+"/getuser")] HttpRequest req, ILogger log, ClaimsPrincipal claimsPrincipal)
{
log.LogInformation("C# HTTP trigger function processed a request started");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
AuthendicateModel data = JsonConvert.DeserializeObject<AuthendicateModel>(requestBody);
var user = req.HttpContext.User;
var identity = claimsPrincipal.Identity;
var details = _userService.Username();
log.LogInformation("C# HTTP trigger function processed a request.");
return new OkObjectResult(new ApiResponse(HttpStatusCode.OK, details, ResponseMessageEnum.Success.ToString()));
}