Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a JWT token with custom JSON claims in Payload using .Net (C#) in Asp.NET Core WEB API

I am generating token with a below code with simple JSON data

  [HttpPost("Token")]
     public IActionResult Token(string userid)
    {
        if ((!string.IsNullOrEmpty(userid)))
        {
            var user = webuserprovider.GetWebUser(userid);

            // validate for 0 records 
            if (user.Count() > 0)
            {
               // if user return 1 row
               var claimsdata = new[]
               { 
                     new  Claim("id",user.First().UserID),                     
               };
                
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretKey"));
                var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                      users:{ "id": user.First().UserID},
                      issuer: "mysite.com",
                      audience: "yoursite.com",
                      expires: DateTime.Now.AddMinutes(3),
                      claims: claimsdata,                      
                    signingCredentials: signInCred
                    );
                  var jwt = new JwtSecurityTokenHandler().WriteToken(token);
                  return Ok(new {jwt});
               // return Ok( new JwtSecurityTokenHandler().WriteToken(token) );
            }
            else
            {// return BadRequest(new { message = "UserID does not exist" }); }
             // return BadRequest("Could not verify user");
                return NotFound();
            }
        }
        return Unauthorized();

    }
}
}

JWT payload data :

     {
      "id": "1234",
     "exp": 1538637844,
      "iss": "mysite.com"
      }

How to create payload data with custom claims like below in C# in Asp.net Core Web API REST? With User id inside { } in payload data -->

  {
   "id": "1234",
   "exp": 1538637844,
   "iss": "mysite.com"
   "user": {
          "id" :"user1"
           }                           
  }
    
like image 303
Jim Lobo Avatar asked Oct 04 '18 07:10

Jim Lobo


People also ask

What is claim in JWT C#?

Claims in JWT Token are used to store key data (e.g. username, timezone, or roles) in the Token payload, besides the IssuedAt (i.e. iat), which is added by default.\ In .NET Core, Claims can be used without installing any additional package, it comes from the System.Security.Claims package.


2 Answers

Here is the Code with

[HttpPost("Token")]
public IActionResult Token(string userid)
{
    if ((!string.IsNullOrEmpty(userid)))
    {
        var user = webuserprovider.GetWebUser(userid);

        // validate for 0 records 
        if (user.Count() > 0)
        {
           // if user return 1 row
           var claimsdata = new[]
           { 
                 new  Claim("subject","custom claims"),                     
           };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretKey"));
            var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                  users:{ "id": user.First().UserID},
                  issuer: "mysite.com",
                  audience: "yoursite.com",
                  expires: DateTime.Now.AddMinutes(3),
                  claims: claimsdata,                      
                signingCredentials: signInCred
                );
               //custom claims as per  requirements
                var jsonu = new { id = user.First().UserID };
                token.Payload["user"] = jsonu;
               //End of custom claims
              var jwt = new JwtSecurityTokenHandler().WriteToken(token);
              return Ok(new {jwt});
           // return Ok( new JwtSecurityTokenHandler().WriteToken(token) );
        }
        else
        {// return BadRequest(new { message = "UserID does not exist" }); }
         // return BadRequest("Could not verify user");
            return NotFound();
        }
    }
    return Unauthorized();
}

And final Payload PAYLOAD: DATA

{
  "subject": "custom claims",
  "exp": 1538651961,
  "iss": "mysite.com",
  "user": {
    "id": "1234"
  }
}
like image 58
Jim Lobo Avatar answered Oct 29 '22 09:10

Jim Lobo


For JWT I typically use JWT nuget package because I don't like how it's done out-of-the-box.

Install-Package JWT 

Check out the documentation. Using this package is pretty straightforward.

var token = new JwtBuilder()
  .WithAlgorithm(new HMACSHA256Algorithm())
  .WithSecret(secret)
  .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds())
  .AddClaim("claim2", "claim2-value")
  .Build();
like image 39
Andrei Avatar answered Oct 29 '22 09:10

Andrei