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"
}
}
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.
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"
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With