作者:捡到宝开封 | 来源:互联网 | 2023-08-18 11:21
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
我正在使用jose jwt库来创建jwt令牌,我不知道如何在有效载荷中使用声明标记。我想存储用户名和一些与之相关的其他数据。下面是我用来生成代码的代码
byte[] secretKey = Base64UrlDecode("-----BEGIN PRIVATE KEY-----");
DateTime issued = DateTime.Now;
DateTime expire = DateTime.Now.AddHours(10);
var payload = new Dictionary()
{
{"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;
1 个解决方案
2
The JWT specification talks about three types of claims: Registered, Public and Private.
JWT规范涉及三种类型的声明:注册,公共和私人。
Registered
注册
The usual ones such as iss
, sub
, exp
, etc.
通常的,如iss,sub,exp等。
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.
IANA JWT索赔注册表用于指定应公开使用以在服务之间标准化它们的声明。这些包含许多有用的,如姓名,电子邮件,地址等。
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).
避免将IANA JWT声明注册表的声明用于其他目的(即不使用名称来存储用户的用户名)可能是个好主意。
So in your case your code could simply be like this to add the username (with the claim from the IANA registry)
因此,在您的情况下,您的代码可能就像这样添加用户名(来自IANA注册表的声明)
byte[] secretKey = Base64UrlDecode("-----BEGIN PRIVATE KEY-----");
DateTime issued = DateTime.Now;
DateTime expire = DateTime.Now.AddHours(10);
var payload = new Dictionary()
{
{"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.
虽然如果它仅供内部使用,我可能只使用用户名或usr自己。
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.
要记住的另一件事(而且很多人都错了)是JWT没有加密任何东西。内容是base64编码的,但任何掌握你的令牌的人都可以读取其中的所有内容。因此,如果用户可以看到它们的可能性很小,请确保不要在其中放置任何敏感内容。