7pass-node-sdk 中文文档教程

发布于 4年前 浏览 36 项目主页 更新于 3年前

7Pass NodeJS SDK

7Pass NodeJS SDK 是一个用于与 7Pass SSO 服务。 你可以使用这个库来 为您的网站实施身份验证并利用 7Pass SSO 提供的已有功能。

Installation

要安装包,请运行以下命令:

npm install 7pass-node-sdk

Running the example application

为了演示库的功能,有一个 交互式教程/指南可用。 在我们开始设置之前 它起来,你需要你的网络应用程序的客户端。 客户代表 与您要验证的服务关联的实体 到。

要获取客户端凭据,您首先需要联系 7Pass 技术团队。

获得可用凭据后,您可以继续运行应用程序。

首先需要安装 SDK 库依赖项:

npm install

然后转到 example_app 目录并安装示例应用程序依赖项:

cd example_app
npm install

创建本地配置文件:

cp config.local.js.example config.local.js

编辑 config.local.js 文件在你最喜欢的编辑器中填写 细节。 您应该掌握所有参数 在您的客户端设置之后。 为了进行测试,请将环境设置为 <代码>质量保证。 一旦完成,您就可以启动应用程序了:

npm start

示例应用程序现在应该可以在 <代码>http://localhost:8000。 该应用程序将指导您完成 该库最常见的用例并向您展示代码示例和 沿途的服务器响应。

API Usage

强烈建议您首先查看示例应用程序。 它 将向您展示带有更多注释和实际值的 API 调用。 它 还将向您展示来自 7Pass SSO 服务的真实响应 你进步。

要使用该库,必须使用 我们要使用的客户端的凭据。 如果你没有 还没有凭据,请参阅上文。

  • client_id (required)
  • client_secret (required)

如果您正在开始开发,那么工作总是一个好主意 针对 7Pass SSO 服务的非实时实例。 指定 您要针对其发出的实例(环境) 请求,您可以将一个名为 environment 的附加键传递给 配置。 目前有两个环境在运行:QA 和 生产。 不要忘记之前切换到生产版本 您向公众发布您的应用程序。

var sevenpass = require('7pass-node-sdk');

var config = {
  client_id: 'YOUR_CLIENT_ID',
  client_secret: 'YOUR_CLIENT_SECRET',
  environment: 'qa' // Optional, defaults to 'production'
};

// 1. Create and initialize the configuration object
// Configuration object fetches OpenID Configuration and JWT public key endpoints
sevenpass.Configuration.createAndInit(config, function(err, ssoConfig) {
  if(err) {
    throw err;
  }

  // 2. Create 7Pass SSO object passing initialized Configuration object
  var sso = new sevenpass.SSO(ssoConfig);

  //your app code continues here.
});

对于这两种环境,都有一个默认的 host URL,可以在其中访问 7Pass API 端点。 对于 production 环境,它是 https://sso.7pass.de,对于 qa,主机是 https://sso.qa.7pass.ctf.prosiebensat1.com。 如果需要,可以通过在配置中指定 host 来覆盖它,如下所示:

var config = {
    host: 'https://mysubdomain.7pass.de',
    // ... other config values
};

Authentication flow

身份验证过程很简单,高级视图如下 如下:用户被重定向到 7Pass SSO 服务,使用 特制的 URL 和他/她登录(或注册)。 一旦用户 已完成该过程,他/她将被重定向回您的 URL 中带有特殊代码的应用程序。 然后应用程序将 使用代码以获取用户的详细信息。 该过程可能会有所不同 取决于传递的选项。

1. Get a redirect URL

该库自动处理 URL 的生成 需要重定向用户。 唯一需要的参数是 redirect_uri 网址。 URL 必须是绝对的,可以是任意的 (假设它已向客户注册)但按照惯例 导致同一主机和称为“回调”的路由。

使用状态 参数是可选的,但建议避免 CSRF 攻击

  • the value is usually stored in the session and is also used with sso.authorization().callback() method when handling the callback request.
options = {
  redirect_uri: 'https://example.com/callback', // Required.
  scope: 'openid profile email', // Optional, default value.
  response_type: 'code' // Optional, default value.
  state: sessionState // Optional, but recommended to avoid CSRF attacks
};

redirectUrl = sso.authorization().authorizeUri(options);

该库将自动设置 client_idnonce(a 唯一请求标识符)参数自动。

2. Redirect an user

现在是时候将用户重定向到生成的 URL 了。

3. Handling 7Pass callback

用户完成登录/注册对话框后,他/她 被重定向到带有标志结果的 redirect_uri URL 过程中。 用户可能已成功通过身份验证,但也 可能已决定取消该过程或可能出现其他错误 已经发生了。 因此,正确的错误处理很重要。

每当发生错误时,都会出现两个查询参数 在 URL 中 - errorerror_description。 错误参数 包含一个错误代码并且 error_description 包含一个人 适合直接显示的错误的可读描述 用户。

您可以选择手动处理错误,如下所示。 否则,如果出现错误, sso.authorization().callback() 回调收到 AuthorizeCallbackException 错误。

// 1. Check if query params contain callback error
if(queryParams.error) {
  var error = queryParams.error;
  var errorDescription = queryParams.error_description;

  // 2. Handle the error and display appropriate message to your end-user.
}

该库自行处理检索令牌,您只需要提供 redirect_uri 以及请求中的查询参数。 这允许您检索可用于稍后获取有关用户的实际信息的令牌。 这些令牌特定于特定用户并且是私有的。 您需要妥善保管它们,不要与任何人分享。

sessionState 参数是可选的,但应该提供相同的参数 如果与 sso.authorization().authorizeUri() 方法一起使用。 提供状态值时收到 AuthorizeCallbackException 回调错误,并且 从查询参数中检索到的不匹配。

// queryParams variable below contains query parameters from the current URL

// 1. Request access token
sso.authorization().callback(callbackUri, queryParams, sessionState, function(err, tokens) {
  if(err) {
    throw err;
  }

  // 2. Store tokens into the user's session storage. You might also want
  //    to store them in your persistent storage (i.e. your database) or
  //    any other storage of your own choosing.
});

收到的响应将具有以下结构。 跑过 示例应用程序以查看实际值。

{
  "access_token": ACCESS_TOKEN,
  "token_type": "Bearer",
  "refresh_token": REFRESH_TOKEN,
  "expires_in": 7200,
  "id_token": JWT_STRING,
  "received_at": RECEIVED_AT_TIMESTAMP,
  "id_token_decoded": DECODED_JWT
}

注意:id_token_decoded 值是从 id_token 解码而来的 场并验证。 如果令牌验证失败,则抛出错误。

4. Caching an access token

令牌在类型的单个对象中表示 <代码>令牌集。 您现在可以将令牌存储到用户的会话存储中。 您可能还想将它们存储在您的持久存储(即您的数据库)或 您自己选择的任何其他存储。

访问令牌在指定的一定时间内有效 expires_in 字段中的秒数。 一旦访问令牌过期,它 无法再使用。 您可以使用刷新获得一个新的 令牌如下:

var TokenSet = require('7pass-node-sdk').TokenSet;

function getFreshTokens(callback) {
  // 1. Create TokenSet object - tokensData contains hash of tokens data as retrieved from user's session
  tokens = new TokenSet(tokensData);

  // 2. Check whether the access token has expired and return immediately if not.
  if(!tokens.isAccessTokenExpired()) {
    return callback(null, tokens);
  }

  // 3. Refresh tokens
  sso.authorization().refresh(tokens, function(err, refreshedTokens) {
    if(err) {
      return callback(err);
    }

    // 4. Store the refreshed tokens back into user's session storage.

    // 5. Return fresh tokens
    callback(null, refreshedTokens)
  });
}

getFreshTokens(function(err, tokens) {
  // Now when you made sure tokens are fresh, you can use them further to create API clients.
})

注意:上面的refresh() 方法也接受像{ refresh_token: 'REFRESH_TOKEN' } 这样的对象作为参数。

5. Calling our API endpoints

现在我们确保令牌是最新的,我们可以开始制作 向 7Pass SSO 服务请求获取用户数据。

与前面的示例相同,运行示例应用程序查看 真正的服务器响应。

// Create a client object using the tokens
var accountClient = sso.accountClient(tokens);

accountClient.get('me', function(err, data) {
  // Handle error

  // 'data' variable contains the response data
});

7Pass SSO 服务提供了相当多的此类端点。 学习 更多关于他们的信息,你可以去 官方文档的概述

Client Credentials requests

该库支持多种类型的“客户端”。 这些客户 通常在所需的配置参数和 之后在他们提供的功能中。 “客户凭证” client 是一种特殊的客户端,它与用户无关 帐户,只能用于调用“客户端”API。

您可以在 文档 accessType 参数等于 client

var sevenpass = require('7pass-node-sdk'), sso;

var config = {
  client_id: 'YOUR_CLIENT_ID',
  client_secret: 'YOUR_CLIENT_SECRET',
  environment: 'qa' // Optional, defaults to 'production'
};

// 1. Create and initialize the configuration object
// Configuration object fetches OpenID Configuration and JWT public key endpoints
sevenpass.Configuration.createAndInit(config, function(err, ssoConfig) {
  if(err) {
    throw err;
  }

  // 2. Create 7Pass SSO object passing initialized Configuration object
  sso = new sevenpass.SSO(ssoConfig);

  // 3. Get the tokens using the client credentials grant type
  sso.authorization().clientCredentials(handleClientCredentialsAuthorization);
});

function handleClientCredentialsAuthorization(err, tokens) {
  if(err) {
    throw err;
  }

  // 4. Use the client as you normally would when using the standard access
  var clientCredentialsClient = sso.clientCredentialsClient(tokens);
  clientCredentialsClient.post('checkPassword', {
    password: 'PASSWORD'
  }, function(err, data) {
    //handle response
  });
}

Device flow

借助设备流,人们可以轻松安全地登录应用程序和服务 在输入或显示功能有限的设备上使用他们的 7Pass 帐户。 这包括智能电视、数码相框或物联网设备。

该设备(您的应用程序)指示最终用户使用另一台计算机或设备并连接 向 7Pass 批准访问请求。 由于您的应用程序无法接收 传入请求,它会反复轮询 7Pass 授权服务器,直到 最终用户完成审批流程。

您的应用程序通过请求一组验证来启动流程 通过发出 HTTP POST 请求从授权服务器获取代码 到令牌端点。

sso.authorization().deviceCode(function(err, deviceCodeResponse) {
    // handle error

    // deviceCodeReponse - see example below
});

deviceCodeResponse 将是如下对象:

{
    code: CODE         // used along with poll requests (see below)
    user_code: Q9CFLH  // the code which user should enter on LINK page 
    expires_in: 600    // expiration of the code (in seconds) 
    interval: 5        // recommended interval for repeating poll requests (in seconds)
    link: LINK_URL     // verification URL user should use to authenticate
    link_qr: IMAGE_URL // image URL of QR code encoded link
}

现在应该提示用户访问另一台设备上的 link URL 以 输入 <代码>用户代码。 link_qr 是表示二维码编码的图像的 URL link URL。 这可以供使用移动设备的用户使用,他们可以扫描它并打开 link URL 在他们的移动浏览器中,而无需自己手动输入。

当用户尝试在 link URL 上进行身份验证时,您的应用程序会反复轮询 7Pass 服务器。 推荐的间隔在 interval 值中指定。

以下示例中的 code 可以是从 sso.authorization().deviceCode() 方法调用接收到的 deviceCodeResponse 对象, 具有 code 属性的对象或只是具有 code 值的字符串。

// repeat every [interval] seconds.
sso.authorization().deviceCodePoll(code, function(err, response) {
    if (err) {
        // handle the error appropriately
        // if OAuth2 error: err.error is set to one of error codes 'code_expired', 'slow_down', 'invalid_grant'
        return;
    }

    // reponse === false in case 'authorization_pending' response is received

    if (response !== false) {
        // reponse is TokenSet object
        // stop polling - user has authorized from another device successfully
    }
});

Backoffice requests

该库还可用于执行“后台”请求。 这些 请求是在没有用户直接参与的情况下发起的,并且 用于管理目的。 你的客户需要有 backoffice_code 授权类型允许。 你还需要知道的ID 您要与之合作的用户。

后台请求用于代表其他用户进行 API 调用。 获取这些请求的访问令牌 您需要使用提供帐户 id 的特殊授权类型“backoffice代码”。 身份验证成功后,您将获得与使用上述标准流程相同的令牌集。

var sevenpass = require('7pass-node-sdk');

var config = {
  backoffice_key: 'YOUR_BACKOFFICE_KEY',
  service_id: 'YOUR_SERVICE_ID',
  environment: 'qa' // Optional, defaults to 'production'
};

// 1. Create and initialize the configuration object
// Configuration object fetches OpenID Configuration and JWT public key endpoints
sevenpass.Configuration.createAndInit(config, function(err, ssoConfig) {
  if(err) {
    throw err;
  }

  // 2. Create 7Pass SSO object passing initialized Configuration object
  var sso = new sevenpass.SSO(ssoConfig);

  // 3. Get the tokens using the backoffice
  sso.authorization().backoffice({
    account_id: 'ACCOUNT_ID' // Required, the ID of the user you want to access
  }, handleBackofficeAuthorization);
});

function handleBackofficeAuthorization(err, tokens) {
  if(err) {
    throw err;
  }

  // 4. Use the client as you normally would when using the standard access
  var aaccountClient = sso.accountClient(tokens);
  accountClient.get('me', function(err, data) {
    //handle response
  });
}

响应将像往常一样。 获得令牌后,7Pass SSO 服务将像访问令牌已使用 “标准”方式。

Client/backoffice registration

当您使用注册新用户时 客户端或后台注册 API, 您可能希望将它们反弹到 7Pass SSO 服务,以便创建用户会话并让用户登录。

此 SDK 提供了一个名为 autologinUri() 的方法,可用于生成重定向(反弹)网址。 该方法接受 TokenSet 作为其第一个参数。 您可以在使用注册 API 时检索用户的令牌 通过提供 scope 参数。 请参阅注册 API 文档以获取更多详细信息。 response_type 默认为 none 但可以设置为任何其他 支持的类型 如果需要的话。

// client is an instance of ApiClient created using sso.clientCredentialsClient() or sso.backofficeClient() methods.
client.post('registration', {
    scope: 'openid profile email'
    // other parameters
}, function(err, response) {
    //handle error

    var tokens = TokenSet.receiveTokens(response);

    var uri = sso.authorization().autologinUri(tokens, {
        redirect_uri: callbackUri, // Required
        state: sessionState // Optional but recommended to use
    }, {
        remember_me: true // Default value: false
    });

    // Redirect user to uri
});

与其他普通授权请求一样,您可以使用 sso.authorization().callback() 方法 处理回调请求。 如果 response_type 设置为 none,回调将接收 null。

Running the tests

该库使用 mocha 进行测试。

npm test

7Pass NodeJS SDK

7Pass NodeJS SDK is a JS library for interacting with the 7Pass SSO service. You can use this library to implement authentication for your website and take advantage of the already existing features that 7Pass SSO offers.

Installation

To install the package, run the following:

npm install 7pass-node-sdk

Running the example application

To demonstrate the functionality of the library, there's an interactive tutorial / guide available. Before we get started setting it up, you need your web application's client. The client represents the entity which is associated with a service you want to authenticate to.

To obtain the client credentials, you first need to contact the 7Pass Tech Team.

Once you have the credentials available, you can go ahead and run the application.

First SDK library dependencies need to be installed:

npm install

Then you go to the example_app directory and install example application dependencies:

cd example_app
npm install

Create the local configuration file:

cp config.local.js.example config.local.js

Edit the config.local.js file in your favorite editor and fill out the details. You should have all of the parameters at your disposal after your client is set up. For testing, keep the environment set to qa. Once that's done, you can start the application:

npm start

The example application should be now available at http://localhost:8000. The application will guide you through the most common use cases of the library and show you code examples and server responses along the way.

API Usage

You strongly encouraged to go over the example application first. It will show you the API calls with more comments and real values. It will also show you the real responses from the 7Pass SSO service as you progress.

To use the library, it's necessary to initialize it with the credentials of the client we want to use. If you don't have the credentials yet, please see above.

  • client_id (required)
  • client_secret (required)

If you're starting the development, it's always a good idea to work against a non live instance of the 7Pass SSO service. To specify the instance (the environment) against which you want to issue the requests, you can pass an additional key called environment to the configuration. There are currently two environments running: QA and production. Don't forget to switch to the production version before you release your application to the public.

var sevenpass = require('7pass-node-sdk');

var config = {
  client_id: 'YOUR_CLIENT_ID',
  client_secret: 'YOUR_CLIENT_SECRET',
  environment: 'qa' // Optional, defaults to 'production'
};

// 1. Create and initialize the configuration object
// Configuration object fetches OpenID Configuration and JWT public key endpoints
sevenpass.Configuration.createAndInit(config, function(err, ssoConfig) {
  if(err) {
    throw err;
  }

  // 2. Create 7Pass SSO object passing initialized Configuration object
  var sso = new sevenpass.SSO(ssoConfig);

  //your app code continues here.
});

For both environments there is a default host URL where 7Pass API endpoints can be reached on. For production environment it is https://sso.7pass.de and for qa a host is https://sso.qa.7pass.ctf.prosiebensat1.com. If needed, this can be overwritten by specifying host in the configuration as below:

var config = {
    host: 'https://mysubdomain.7pass.de',
    // ... other config values
};

Authentication flow

The authentication process is simple and the high level view is as follows: The user is redirected to the 7Pass SSO service using a specially crafted URL and he/she signs in (or signs up). Once the user has finished the process, he/she is redirected back to your application with a special code in the URL. The application will then use the code in order to get the user's details. The process may vary depending on the passed options.

1. Get a redirect URL

The library automatically handles the generation of the URL to which the user needs to be redirected. The only required parameter is the redirect_uri URL. The URL needs to be absolute and can be arbitrary (given that it is registered to the client) but will by convention lead to the same host and a route called "callback".

Use of state parameter is optional but recommended to avoid CSRF attacks

  • the value is usually stored in the session and is also used with sso.authorization().callback() method when handling the callback request.
options = {
  redirect_uri: 'https://example.com/callback', // Required.
  scope: 'openid profile email', // Optional, default value.
  response_type: 'code' // Optional, default value.
  state: sessionState // Optional, but recommended to avoid CSRF attacks
};

redirectUrl = sso.authorization().authorizeUri(options);

The library will automatically set the client_id and nonce (a unique request identifier) parameters automatically.

2. Redirect an user

Now it's time to redirect the user to the generated URL.

3. Handling 7Pass callback

After the user has finished with the sign in/up dialog, he/she has been redirected to the redirect_uri URL with the outcome of the sign in process. The user might have successfully authenticated but also might have decided to cancel the process or some other error might have happened. Therefore it's important have proper error handling.

Whenever an error occurs, there will be two query parameters present in the URL - error and error_description. The error parameter contains an error code and the error_description contains a human readable description of the error suitable for direct displaying to the user.

You might choose to handle an error manually as below. Otherwise in case of an error, sso.authorization().callback() callback receives AuthorizeCallbackException error.

// 1. Check if query params contain callback error
if(queryParams.error) {
  var error = queryParams.error;
  var errorDescription = queryParams.error_description;

  // 2. Handle the error and display appropriate message to your end-user.
}

The library handles retrieving the tokens on its own, you just need to provide the redirect_uri and also query parameters from the request. This allows you to retrieve the tokens which can be used to fetch the actual information about the user later. These tokens are specific to the particular user and are private. You need to keep them secured and do not share them with anybody.

sessionState parameter is optional but same should be provided if used with sso.authorization().authorizeUri() method. AuthorizeCallbackException callback error is received when state value provided and the one retrieved from query parameters do not match.

// queryParams variable below contains query parameters from the current URL

// 1. Request access token
sso.authorization().callback(callbackUri, queryParams, sessionState, function(err, tokens) {
  if(err) {
    throw err;
  }

  // 2. Store tokens into the user's session storage. You might also want
  //    to store them in your persistent storage (i.e. your database) or
  //    any other storage of your own choosing.
});

The received response will have the following structure. Run the example application to see the real values.

{
  "access_token": ACCESS_TOKEN,
  "token_type": "Bearer",
  "refresh_token": REFRESH_TOKEN,
  "expires_in": 7200,
  "id_token": JWT_STRING,
  "received_at": RECEIVED_AT_TIMESTAMP,
  "id_token_decoded": DECODED_JWT
}

Note: The id_token_decoded value is decoded from the id_token field and verified. If token verification fails, the error is thrown.

4. Caching an access token

The tokens are represented in a single object of type TokenSet. You can now store tokens into the user's session storage. You might also want to store them in your persistent storage (i.e. your database) or any other storage of your own choosing.

Access tokens are valid for certain amount of time specified in seconds in the expires_in field. Once the access token expires, it can no longer be used. You can obtain a new one using the refresh token as follows:

var TokenSet = require('7pass-node-sdk').TokenSet;

function getFreshTokens(callback) {
  // 1. Create TokenSet object - tokensData contains hash of tokens data as retrieved from user's session
  tokens = new TokenSet(tokensData);

  // 2. Check whether the access token has expired and return immediately if not.
  if(!tokens.isAccessTokenExpired()) {
    return callback(null, tokens);
  }

  // 3. Refresh tokens
  sso.authorization().refresh(tokens, function(err, refreshedTokens) {
    if(err) {
      return callback(err);
    }

    // 4. Store the refreshed tokens back into user's session storage.

    // 5. Return fresh tokens
    callback(null, refreshedTokens)
  });
}

getFreshTokens(function(err, tokens) {
  // Now when you made sure tokens are fresh, you can use them further to create API clients.
})

Note: refresh() method above also accepts object like { refresh_token: 'REFRESH_TOKEN' } as an argument.

5. Calling our API endpoints

Now that we're sure the tokens are up to date, we can start making requests to the 7Pass SSO service to get the user data.

Same as with the previous example, run the example application to see the real server response.

// Create a client object using the tokens
var accountClient = sso.accountClient(tokens);

accountClient.get('me', function(err, data) {
  // Handle error

  // 'data' variable contains the response data
});

The 7Pass SSO service offers quite a few of these endpoints. To learn more about them, you can go to the official documentation's overview.

Client Credentials requests

The library supports multiple types of "clients". These clients generally differ in the required configuration parameters and afterwards in the functionality they provide. The "client credentials" client is a special kind of client which is not associated with a user account and can be only used to call the "clients" APIs.

You can see all of the available endpoints in the documentation with the accessType parameter equal to client.

var sevenpass = require('7pass-node-sdk'), sso;

var config = {
  client_id: 'YOUR_CLIENT_ID',
  client_secret: 'YOUR_CLIENT_SECRET',
  environment: 'qa' // Optional, defaults to 'production'
};

// 1. Create and initialize the configuration object
// Configuration object fetches OpenID Configuration and JWT public key endpoints
sevenpass.Configuration.createAndInit(config, function(err, ssoConfig) {
  if(err) {
    throw err;
  }

  // 2. Create 7Pass SSO object passing initialized Configuration object
  sso = new sevenpass.SSO(ssoConfig);

  // 3. Get the tokens using the client credentials grant type
  sso.authorization().clientCredentials(handleClientCredentialsAuthorization);
});

function handleClientCredentialsAuthorization(err, tokens) {
  if(err) {
    throw err;
  }

  // 4. Use the client as you normally would when using the standard access
  var clientCredentialsClient = sso.clientCredentialsClient(tokens);
  clientCredentialsClient.post('checkPassword', {
    password: 'PASSWORD'
  }, function(err, data) {
    //handle response
  });
}

Device flow

With device flow people can easily and safely log into apps and services with their 7Pass account on devices with limited input or display capabilities. This includes Smart TVs, digital photo frames, or Internet of Things devices.

The device (your application) instructs the end-user to use another computer or device and connect to 7Pass to approve the access request. Since your application cannot receive incoming requests, it polls the 7Pass authorization server repeatedly until the end-user completes the approval process.

Your application initiates the flow by requesting a set of verification codes from the authorization server by making an HTTP POST request to the token endpoint.

sso.authorization().deviceCode(function(err, deviceCodeResponse) {
    // handle error

    // deviceCodeReponse - see example below
});

deviceCodeResponse would be object like the following:

{
    code: CODE         // used along with poll requests (see below)
    user_code: Q9CFLH  // the code which user should enter on LINK page 
    expires_in: 600    // expiration of the code (in seconds) 
    interval: 5        // recommended interval for repeating poll requests (in seconds)
    link: LINK_URL     // verification URL user should use to authenticate
    link_qr: IMAGE_URL // image URL of QR code encoded link
}

The user should now be prompted to visit link URL on another device to enter user_code. link_qr is URL of an image representing QR code encoded link URL. This could be used by users using mobile devices, they can scan it and have link URL opened in their mobile browsers without manually typing it themselves.

While user tries to authenticate on link URL, your application polls 7Pass server repeatedly. Recommended interval is specified in interval value.

code in the example below can be either deviceCodeResponse object received from sso.authorization().deviceCode() method call, object with code property or simply a string with code value.

// repeat every [interval] seconds.
sso.authorization().deviceCodePoll(code, function(err, response) {
    if (err) {
        // handle the error appropriately
        // if OAuth2 error: err.error is set to one of error codes 'code_expired', 'slow_down', 'invalid_grant'
        return;
    }

    // reponse === false in case 'authorization_pending' response is received

    if (response !== false) {
        // reponse is TokenSet object
        // stop polling - user has authorized from another device successfully
    }
});

Backoffice requests

The library can also be used to perform "backoffice" requests. These requests are initiated without direct involvement of users and are meant for administrative purposes. Your client needs to have the backoffice_code grant type allowed. You also need to know the ID of the user you want to work with.

Backoffice requests are used to make an API calls on behalf of other users. To get access token for these requests you need to use special grant type 'backofficecode' providing an accountid. Upon successful authentication you get a same token set as using standard flow described above.

var sevenpass = require('7pass-node-sdk');

var config = {
  backoffice_key: 'YOUR_BACKOFFICE_KEY',
  service_id: 'YOUR_SERVICE_ID',
  environment: 'qa' // Optional, defaults to 'production'
};

// 1. Create and initialize the configuration object
// Configuration object fetches OpenID Configuration and JWT public key endpoints
sevenpass.Configuration.createAndInit(config, function(err, ssoConfig) {
  if(err) {
    throw err;
  }

  // 2. Create 7Pass SSO object passing initialized Configuration object
  var sso = new sevenpass.SSO(ssoConfig);

  // 3. Get the tokens using the backoffice
  sso.authorization().backoffice({
    account_id: 'ACCOUNT_ID' // Required, the ID of the user you want to access
  }, handleBackofficeAuthorization);
});

function handleBackofficeAuthorization(err, tokens) {
  if(err) {
    throw err;
  }

  // 4. Use the client as you normally would when using the standard access
  var aaccountClient = sso.accountClient(tokens);
  accountClient.get('me', function(err, data) {
    //handle response
  });
}

The response will be as usual. Once you get the tokens, the 7Pass SSO service will act as if the access token has been obtained using the "standard" way.

Client/backoffice registration

When you register new users using the client or backoffice registration API, you might want to bounce them to the 7Pass SSO service so that the user's session is created and the user logged in.

This SDK provides a method called autologinUri() which can be used to generate the redirect (bounce) URL. The method accepts a TokenSet as its first parameter. You can retrieve the user's tokens when using the registration API by providing the scope parameter. See the registration API documentation for more details. response_type defaults to none but can be set to any other supported type if needed so.

// client is an instance of ApiClient created using sso.clientCredentialsClient() or sso.backofficeClient() methods.
client.post('registration', {
    scope: 'openid profile email'
    // other parameters
}, function(err, response) {
    //handle error

    var tokens = TokenSet.receiveTokens(response);

    var uri = sso.authorization().autologinUri(tokens, {
        redirect_uri: callbackUri, // Required
        state: sessionState // Optional but recommended to use
    }, {
        remember_me: true // Default value: false
    });

    // Redirect user to uri
});

As with other ordinary authorize requests, you can use sso.authorization().callback() method to handle a callback request. The callback receives null if response_type was set to none.

Running the tests

The library uses mocha for testing.

npm test
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文