6

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"
           }                           
  }
    

2 Answers 2

12

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"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

9

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.