@api-components/api-authorization

中文文档
0.7.2发布于 2022/10/21Apache-2.0ESM + CJS近 30 天下载 3075

A custom element to render authorization editor with the support of the AMF model.

原始使用文档
文档目录11 节
  1. Usage
  2. Installation
  3. In an html file
  4. In a LitElement
  5. Applying AMF model
  6. Authorization settings
  7. Applying authorization settings
  8. Additional steps
  9. Development
  10. Running the demo locally
  11. Running the tests

DEPRECATED

This component is deprecated. The code base has been moved to api-request module.


A custom element that renders and manages authorization state in AMF powered application.

After applying the AMF model and security scheme for an operation the element decides which method to render, list of possible methods, manages state when the user change any of the values, and provides validation methods for the UI.

If authorization method operates on headers or query parameters this component dispatches corresponding change event so other component can update the sate.

More complex authorization schemes like OAuth 1or OAuth 2 first require obtaining access token. Once the token is obtained then validation state is updated and corresponding delivery method is used (header or query parameter).

This element support security description for both RAML and OAS.

  • OAuth 2
  • OAuth 2 with annotation (see RAML's docs)
  • OAuth 1
  • RAML custom scheme
  • Pass Through
  • Api Key (OAS)
  • Bearer (OAS)

Note, Digest authorization method is not supported at the time. If you are interested in this method, please, let us know. This component fully support all OAS security schemes.

Usage

The component extends @advanced-rest-client/authorization package to add API model support. The base component renders basic authorization methods. The element requires to apply AML's JSON+LD model to the amf property and scheme definition to the security property.

Installation

npm install --save @api-components/api-authorization

In an html file

<html>
  <head>
    <script type="module">
      import '@api-components/api-authorization/api-authorization.js';
    </script>
  </head>
  <body>
    <api-authorization-method redirectUri="..."></api-authorization-method>
    <script>
    (async () => {
      const model = await getAmfModel();
      const security = getSecurity(model, '/endpoint', 'get');
      const element = document.querySelector('api-authorization');
      element.amf = model;
      element.security = security;
      element.onchange = (e) => {
        if (e.target.validate()) {
          const authList = e.target.serialize();
          console.log(authList);
        }
      };
    })();
    </script>
  </body>
</html>

In a LitElement

import { LitElement, html } from 'lit-element';
import '@api-components/api-authorization/api-authorization.js';

class SampleElement extends LitElement {
  static get properties() {
    return {
      amfModel: { type: Array },
      endpoint: { type: String },
      method: { type: String },
    };
  }

  get security() {
    const { amfModel, endpoint, method } = this;
    return this.readSecurityFor(amfModel, endpoint, method);
  }

  readSecurityFor(amf, endpoint, method) {
    // implement me
  }

  _authChanged(e) {
    if (e.target.validate()) {
      const authList = e.target.serialize();
      console.log(authList);
    }
  }

  render() {
    const { amfModel, security } = this;
    return html`
    <api-authorization
      .amf="${amfModel}"
      .security="${security}"
      @change={this._authChanged}
    ></api-authorization-method>`;
  }
}
customElements.define('sample-element', SampleElement);

Applying AMF model

First step is to pass the generated AMF model to the amf property. It is required to properly resolve internal model dependencies and to read keys in JSON+LD compact model.

Second step is to extract the correct security definition for an operation. It is added to a http://a.ml/vocabularies/apiContract#supportedOperation object. It should be an array of all supported by the operation methods.

An example script that applies the values can look like the following.

<api-authorization-method type="OAuth 2" id="auth"></api-authorization-method>
<script>
(async () => {
  const model = await getAmfModelSomehow();
  const security = readSecurityFor(model, '/endpoint', 'GET');
  const method = document.getElementById('auth');
  method.amf = model;
  method.security = security;
})();
</script>

The getAmfModelSomehow() function can download pre-generated model or run AMF parser directly from RAML or OAS specification. Then the readSecurityFor() function looks for security definition in /endpoint endpoint, inside GET method. When ready the values are applied to the element.

The order of setting amf and security parameters doesn't matter as the data processing starts asynchronously.

A note on clearing settings property. When an undefined or any incompatible value is set to the settings property, the component renders nothing and sets aria-hidden attribute.

Authorization settings

An API may define more than one authorization method to be applied to a request. This is possible with OAS defined APIs, RAML has no such concept. Because of that the settings getter (or serialize() function) returns an array of applied authorization settings.

Each object has type and valid properties. The type is one of the supported by the @api-components/api-authorization-method values for type attribute. The valid property is a result of validating the element that provides the UI for the authorization method. Additionally each object contains settings property that contains user entered values and configuration read from the API. The properties for this object depends on selected authorization method and it is a result of calling serialize() function on api-authorization-method.

Applying authorization settings

The component does not propagate changes to the headers or query parameters. This should be done before the request is being executed. For that call createAuthParams() method to generate a list of parameters to apply to the request object.

sendRequest() {
  const authCmp = this.shadowRoot.querySelector('api-authorization');
  const auth = authCmp.createAuthParams();
  const request = {
    method: 'GET',
    url: 'https://api.domain.com/path?',
    headers: '',
  };
  Object.keys(auth.headers).forEach((header) => request.headers += `${header}: ${auth.headers[header]}\n`);
  Object.keys(auth.params).forEach((param) => request.url += `${param}=${auth.params[param]}&`);
}

Additional steps

Digest, NTLM

Digest and NTLM authorization methods interacts with the request in a way that makes it impossible to apply the settings to the request before initializing the connection. It requires a series of requests and responses managed on the same connection. Because of that for this two methods the component produces authorization settings only. The hosting application must always check for current authorization settings and if either method is used then perform the authorization when connection is made.

OAuth 1

OAuth 1 authorization is based on signing the request data: HTTP method and the URL. This may change after the authorization is set up. Because of that the application that host this element must sign the request with the authorization header as described in this document. Use settings getter to get current settings.

The @advanced-rest-client/authorization component has signRequest(request, auth) method to sign a request for OAuth 1 protocol.

Example

const settings = node.serialize();
const oauth1 = settings.find((item) => item.type === 'oauth 1');
if (oauth1 && oauth1.valid) {
  const oauth1auth = document.querySelector('oauth1-authorization');
  oauth1auth.signRequest(request, oauth1.settings);
}

Development

git clone https://github.com/advanced-rest-client/api-authorization
cd api-authorization
npm install

Running the demo locally

npm start

Running the tests

npm test

版本与发布记录

@api-components/api-authorization 共发布 11 个版本,首次发布于 2020/04/23;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.7.2latest2022/10/214 年前
0.7.12022/08/114 年前
0.7.02021/09/105 年前
0.6.32021/07/055 年前
0.6.22021/06/155 年前
0.6.12021/03/095 年前

关于 @api-components/api-authorization 的常见问题

@api-components/api-authorization 是什么?

A custom element to render authorization editor with the support of the AMF model.

如何安装 @api-components/api-authorization?

在项目目录运行 npm install @api-components/api-authorization,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:jsrsasign(^10.1.4)、cryptojslib(^3.1.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@api-components/api-authorization 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/api-components__api-authorization 是否存在。

@api-components/api-authorization 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@api-components/api-authorization 可以商用吗?

@api-components/api-authorization 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@api-components/api-authorization 的下载量有多少?

根据 npm 官方下载统计,@api-components/api-authorization 在 2026/10/06 – 2026/11/04 这 30 天内被下载 3,075 次,日均约 103 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@api-components/api-authorization 还在维护吗?

最新版本 0.7.2 发布于 2022/10/21(4 年前);至今共发布 11 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/04/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。