Click here to Skip to main content
15,065,044 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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()));

}


What I have tried:

Written Code like above after accessing user, identity details getting null

var user = req.HttpContext.User;
var identity = claimsPrincipal.Identity;
Posted
Updated 27-Feb-21 22:25pm

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900