Reputation: 83
i am using jose jwt library to creating jwt token, i am not sure how i can i use the claims tag in the payload. i want to store user name and some other data related to it. below is the code which i am using to generate code
byte[] secretKey = Base64UrlDecode("-----BEGIN PRIVATE KEY-----");
DateTime issued = DateTime.Now;
DateTime expire = DateTime.Now.AddHours(10);
var payload = new Dictionary<string, object>()
{
{"iss", "service email"},
{"aud", "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit"},
{"sub", "service email"},
{"iat", ToUnixTime(issued).ToString()},
{"exp", ToUnixTime(expire).ToString()}
};
string token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
return token;
Upvotes: 1
Views: 4663
Reputation: 17522
The JWT specification talks about three types of claims: Registered, Public and Private.
Registered
The usual ones such as iss
, sub
, exp
, etc.
Public claims
The IANA JWT Claims Registry is used to specify the claims that should be used publicly to standardize them between services. These contains lots of useful ones such as name
, email
, address
, etc.
Private claims
If you are only using your token within your own application or between known applications you could actually add whatever claims you want.
It might be a good idea to avoid using claims from the IANA JWT Claims Registry for other purposes though (ie don't use name
to store the users username).
So in your case your code could simply be like this to add the username (with the claim from the IANA registry)
byte[] secretKey = Base64UrlDecode("-----BEGIN PRIVATE KEY-----");
DateTime issued = DateTime.Now;
DateTime expire = DateTime.Now.AddHours(10);
var payload = new Dictionary<string, object>()
{
{"iss", "service email"},
{"aud", "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit"},
{"sub", "service email"},
{"iat", ToUnixTime(issued).ToString()},
{"exp", ToUnixTime(expire).ToString()},
{"preferred_username", "MyAwesomeUsername"}
};
string token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
return token;
Though if it's only for internal use I would probably go with just username
or usr
myself.
Another thing to remember (and that many get wrong) is that JWT isn't encrypting anything. The content is base64 encoded but anyone that get hold of your token can read everything in it. So make sure to not put anything sensitive in them if there is even a slight chance that a user can see them.
Upvotes: 3