密码凭证获取 access_token

客户端可以直接通过调用 Restfull API 根据密码凭证获取 access_token,然后通过 access_token 继续获取认证用户信息

接口地址:

参考地址

https://cas_server_url/oauth2.0/accessToken?grant_type=password&client_id=client&client_secret=123456&username=admin&password=admin

请求方式:

  • GET
  • POST

请求参数:

参数名称 参数说明 请求类型 是否必须 数据类型 schema
grant_type 授权类型常量 password query true string
client_id 应用审核通过后返回的client_id query true string
client_secret 应用审核通过后返回的client_secret query true string
username 用户名 query true string
password 密码 query true string

响应状态

状态码 说明 schema
200 OK

响应示例:

正确时返回:

{
    "access_token": "AT-3-rX4WfOiCgiF6qMNt52PfqDaQj-F4I9LK",
    "token_type": "bearer",
    "expires_in": 28800
}

错误时返回:

{
    "timestamp": 1660987198227,
    "status": 401,
    "error": "Unauthorized",
    "message": "No message available",
    "path": "/oauth2.0/accessToken"
}

响应参数:

参数名称 参数说明 类型 schema
access_token 接口访问令牌 access_token string
token_type 令牌类型:bearer string
expires_in 令牌有效期 integer(int32)

调用示例:

JavaScript - Fetch 示例

var myHeaders = new Headers();
myHeaders.append("service", "https://my_server_url");
myHeaders.append("Content-Type", "application/json");

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  redirect: 'follow'
};

fetch("https://cas_server_url/oauth2.0/accessToken?grant_type=password&client_secret=xxx=&username=xxx&password=xxx&client_id=xxx", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

Java - OkHttp 示例

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
  .url("https://cas_server_url/oauth2.0/accessToken?grant_type=password&client_secret=xxx=&username=xxx&password=xxx&client_id=xxx")
  .method("POST", body)
  .addHeader("service", "https://my_server_url")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();
作者:Jeebiz  创建时间:2022-08-20 18:07
最后编辑:Jeebiz  更新时间:2024-05-07 20:29