3.9.11.1. 获取 OAuth 令牌

任何 REST API 方法都需要 OAuth 令牌(除了使用匿名访问)。可以通过 POST 方式请求此地址获取令牌:

http://localhost:8080/app/rest/v2/oauth/token

此端点使用基本身份验证进行访问保护,REST API 客户端 ID 和密码用于这里的份验证。请注意,这里的客户端 ID 和密码不是应用程序的用户登录名和密码。REST API 客户端 ID 和密码通过应用程序属性 cuba.rest.client.idcuba.rest.client.secret 定义。(默认值分别为 clientsecret)。必须在 Authorization 请求头中以 base64 编码的字符串传递客户端 ID 和密码,客户端 ID 和密码使用冒号(":")分隔。

请求类型必须是 application/x-www-form-urlencoded,编码方式为 UTF-8

请求必须包含以下参数:

  • grant_type - password

  • username - 应用程序用户登录名。

  • password - 应用程序用户密码。

  1. POST /oauth/token
  2. Authorization: Basic Y2xpZW50OnNlY3JldA==
  3. Content-Type: application/x-www-form-urlencoded
  4. grant_type=password&username=smith&password=qwerty123

也可以使用 cURL:

  1. curl -H "Content-type: application/x-www-form-urlencoded" -H "Authorization: Basic Y2xpZW50OnNlY3JldA==" -d "grant_type=password&username=admin&password=admin" http://localhost:8080/app/rest/v2/oauth/token

方法返回一个 JSON 对象:

  1. {
  2. "access_token": "29bc6b45-83cd-4050-8c7a-2a8a60adf251",
  3. "token_type": "bearer",
  4. "refresh_token": "e765446f-d49e-4634-a6d3-2d0583a0e7ea",
  5. "expires_in": 43198,
  6. "scope": "rest-api"
  7. }

访问令牌值在 access_token 属性中。

要使用访问令牌,将其放在带有 Bearer 类型的 Authorization 请求头中,例如:

  1. Authorization: Bearer 29bc6b45-83cd-4050-8c7a-2a8a60adf251

refresh_token 属性包含刷新令牌值。刷新令牌不能用于访问受保护的资源,但它具有比访问令牌更长的生命周期,并且可以用于在当前的访问令牌到期时获取新的访问令牌。

使用刷新令牌获取新访问令牌的请求必须包含以下参数:

  • grant_type - refresh_token.

  • refresh_token - 刷新令牌值.

  1. POST /oauth/token
  2. Authorization: Basic Y2xpZW50OnNlY3JldA==
  3. Content-Type: application/x-www-form-urlencoded
  4. grant_type=refresh_token&refresh_token=e765446f-d49e-4634-a6d3-2d0583a0e7ea

另请参阅以下与令牌相关的应用程序属性: