一类动词二类动词三类动词_基于http动词的完全无效授权技术

一类动词二类动词三类动词

Authorization is a basic feature of modern web applications. It’s a mechanism of specifying access rights or privileges to resources according to user roles. In case of CMS like applications, it needs to be equipped with advanced libraries and authorization techniques. But for minimal applications a full fledged library can be an overhead.

授权是现代Web应用程序的基本功能。 这是一种根据用户角色指定对资源的访问权限或特权的机制。 如果是类似CMS的应用程序,则需要配备高级库和授权技术。 但是对于最少的应用程序来说,完整的库可能会增加开销。

I will discuss a dead simple authorization technique based on HTTP verbs, for this particular purpose.

为此,我将讨论一种基于HTTP动词的简单授权技术。

事前要考虑的事情 (Things to consider beforehand)

This technique isn’t something you can implement anywhere. Use this only if your requirements match the particular scenario.

您无法在任何地方实施此技术。 仅当您的要求符合特定情况时才使用此选项。

  • It works only for REST APIs. Everything happens on middleware layer. If you have a simple MVC based REST APIs, this is for you.

    它仅适用于REST API。 一切都发生在中间件层上。 如果您有一个简单的基于MVC的REST API,则适合您。
  • It heavily relies on the HTTP verbs and the URL naming convention. So API endpoints should be super clear and structured. Similar to some structure like this one.

    它在很大程度上依赖于HTTP动词和URL命名约定。 因此,API端点应该超级清晰和结构化。 类似于这种结构。
List Products  : GET    /products
Product Detail : GET /products/{id}
Create Product : POST /products
Update Product : PUT /products/{id}
Delete Product : DELETE /products/{id}
  • A URL can perform many stuffs; but all cannot be expressed just in its naming and HTTP verb. If you require complex authorization, you can’t just rely on this technique.

    URL可以执行许多工作; 但不能仅使用其命名和HTTP动词来表示所有内容。 如果您需要复杂的授权,则不能仅仅依靠这种技术。

Lets implement the dead simple authorization technique based on HTTP verbs. For demo purpose we will be using Nodejs. You can implement it on any language and platform of your choice: core Nodejs, ExpressJS, aws Lambda etc..

让我们基于HTTP动词实现完全无效的简单授权技术。 出于演示目的,我们将使用Nodejs。 您可以在您选择的任何语言和平台上实现它:核心Node.js,ExpressJS,aws Lambda等。

步骤1:将用户角色编码为JWT令牌 (Step 1: Encode user role into JWT Token)

JWT token is the key thing here. It contains the user role encoded in it. The token is returned when user logs in.

JWT令牌是这里的关键。 它包含其中编码的用户角色。 用户登录时将返回令牌。

const jwt = require(‘jsonwebtoken’);const token = jwt.sign({

role: userData.role
}, JWT_KEY);

On the next API call, the token is passed as the value of Authorization header field.

在下一个API调用中,令牌作为Authorization标头字段的值传递。

Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdW...

第2步:解码令牌并检查权限 (Step 2: Decode token and check permissions)

When request is sent to the web server with JWT token attached on header, it goes through a middleware layer. Inside the layer the token is extracted, decoded. To check for permission we require two information.

当请求发送到带有标头上的JWT令牌的Web服务器时,请求将通过中间件层。 在该层内部,令牌被提取,解码。 要检查许可,我们需要两个信息。

  • User role: decoded from token

    用户角色:从令牌解码
  • Resource name: identified from request URL

    资源名称:从请求URL标识
const jwt = require('jsonwebtoken');


// extract token from header
let authHeader = request.header.Authorization;
let token = authHeader.split(" ")[1];


// decode token and get user's 'role'
let decodedVal = jwt.verify(token, process.env.JWT_KEY);
let role = decodedVal.role;


// get resource name(based on your web framework)
// eg:
// GET /products/1 => 'products'
// PUT /users/3    => 'users'
// POST /orders    => 'orders'
let resourceName = request.url.split("/")[1];

The mechanism of retrieving HTTP verb and resource name may differ according to the language or framework being used. Above code is only for demonstration purpose.

根据所使用的语言或框架,检索HTTP动词和资源名称的机制可能有所不同。 上面的代码仅用于演示目的。

The permissions for resources according to user roles are stored in the following manner. Each of the roles have access to certain resources. Within resources they can perform certain actions determined by HTTP verbs.

根据用户角色的资源许可以以下方式存储。 每个角色都可以访问某些资源。 在资源内,他们可以执行由HTTP动词确定的某些动作。

const PERMISSIONS = {
        "vendor": {
            "products": ["POST", "PUT", "DELETE", "GET"],
            "orders": ["POST", "PUT", "DELETE", "GET"],
            "stores": ["POST", "PUT", "DELETE", "GET"],
            "dashboard": ["GET"]
        },


        "customer": {
            "products": ["GET"],
            "orders": ["GET"],
            "stores": ["GET"],
            "comments": ["GET", "POST"],
            "shopping-carts": ["GET", "POST"],
            "dashboard": ["GET"]
        },


				"admin": {
            "products": ["POST", "PUT", "DELETE", "GET"],
            "orders": ["POST", "PUT", "DELETE", "GET"],
            "stores": ["POST", "PUT", "DELETE", "GET"],
            "comments": ["POST", "PUT", "DELETE", "GET"],
            "shopping-carts": ["POST", "PUT", "DELETE", "GET"],
            "dashboard": ["POST", "PUT", "DELETE", "GET"]
        }
};

The method below returns whether the user is allowed to access the resource or not.

下面的方法返回是否允许用户访问资源。

function checkPermission(role, resource, httpVerb){
	if (PERMISSIONS[role] && PERMISSIONS[role][resource]) 
		return PERMISSIONS[role][resource].includes(httpVerb);
	return false;
}


// Example


// request from "admin" 
// POST https://test-domain.com/products/ => true


// request from "customer" 
// POST https://test-domain.com/products/ => false

Based on the result, the API request can be forwarded to the next middleware layer/controller or the request can be denied with error response.

根据结果​​,可以将API请求转发到下一个中​​间件层/控制器,也可以通过错误响应拒绝该请求。

The approach may work only for certain use cases(as mentioned above). If you have the same scenario, instead of relying on heavy libraries you can implement the technique fast and easy.

该方法可能仅适用于某些用例(如上所述)。 如果您具有相同的方案,则无需依赖繁琐的库,而是可以快速轻松地实现该技术。

What do you think about this technique ? Do you have some other better approach ? Please share it on the comments below.

您如何看待这种技术? 您还有其他更好的方法吗? 请在下面的评论中分享。

翻译自: https://medium.com/@bibhutipd/dead-simple-authorization-technique-based-on-http-verbs-7a2c3cfbde2f

一类动词二类动词三类动词

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值