简体   繁体   English

使用JWT时如何使用权限/角色处理授权

[英]How to handle Authorization with Permission/Roles while using JWT

im facing a problem while implementing authorization in my first nodejs application which uses expressjs, sequelize and jsonwebtoken for authentication. 即时通讯在我的第一个使用expressjs,sequelize和jsonwebtoken进行身份验证的nodejs应用程序中实现授权时遇到问题。 Within I want to forbid/allow routes for different user and i dont want to use another package like oauth2 or something which handles authorization for me. 在我想禁止/允许不同用户的路由,并且我不想使用另一个包,例如oauth2或为我处理授权的东西。

At the moment i have created a jsonwebtoken which has permission roles included within the payload: 目前,我已经创建了一个jsonwebtoken,其有效负载中包含许可权角色:

{ 
    "userid": 1,  
    "name": "John Doe",  
    "permissions" : ["user_get", "user_post", "user_put"]
    "iat": 1505142542,  
    "exp": 1505146142
}

No i want to check within a call like "GET /user" if the authenticated user is allowed to call it. 不,我想检查是否允许经过身份验证的用户调用“ GET / user”之类的调用。

My question is: Is it safe to use this approach or shouldnt I include the permissions within the jwt? 我的问题是:使用这种方法是否安全?是否应该在jwt中包含权限? Another alternative is to ask the database and retrieve the permission instead of checking the payload. 另一种选择是询问数据库并检索权限,而不是检查有效负载。

Additionally the token will be checked if it is still validated in case the server invalidates the user. 另外,如果服务器使用户无效,将检查令牌是否仍然有效。

JWT is safe and good. 智威汤逊安全又好。 If you are aware of OAuth2, you can even implement its simpler version. 如果您知道OAuth2,甚至可以实现其更简单的版本。

  1. Register a user give him a set of credentials suppose an user_id and password (Also called clientid and secret). 注册一个用户,假设他有一个user_id和密码(也称为clientid和secret),则给他一组凭据。
  2. Whenever user registers for first time return a JWT with a set expiry time as you are doing it right now. 用户每次进行首次注册时,都将按照您现在设置的方式将JWT设置为到期时间。
  3. As you mentioned use it to check for permissions. 如前所述,使用它来检查权限。
  4. If JWT expires user can request new one by providing user_id and password. 如果JWT过期,则用户可以通过提供user_id和密码来请求新密码。

Now what I would suggest is if you are not going to use 现在我建议您是否要使用

"userid": 1,  
"name": "John Doe" 

anywhere after validating user's permission to access API then do not keep them in JWT at all. 在确认用户访问API的权限之后,请不要将其完全保留在JWT中。 Instead use a signature for your JWT this way don't need to keep the user details flowing on network. 而是以这种方式为JWT使用签名,而无需保持用户详细信息在网络上流动。 :) :)

Yes, JWT is very safe to keep confidential data. 是的,JWT非常安全地保留机密数据。

For additional setting you can renew the jwt token on each request, So whenever the client send you a jwt token. 对于其他设置,您可以在每个请求上续订jwt令牌,因此,每当客户端向您发送jwt令牌时。 Each request will verify the user using jwt token. 每个请求将使用jwt令牌验证用户。 And each response will send client to new jwt token for next request. 每个响应都会将客户端发送到新的jwt令牌以进行下一个请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM