oauth2.0-各种授权类型示例代码

authorization_code

请求临时令牌

请求

1
https://oauth2server.com/oauth/authorize?client_id=a17c21ed&response_type=code&state=5ca75bd30&redirect_uri=https://oauth2client.com/auth

响应

1
https://oauth2client.com/cb?code=Yzk5ZDczMzRlNDEwY

异常

1
2
3
4
5
HTTP/1.1 2 Found
Location: https://oauth2client.com/redirect?error=access_denied
&error_description=The+user+denied+the+request
&error_uri=https://oauth2server.com/error/access_denied
&state=wxyz1234

交换获取令牌

请求

1
2
3
4
5
6
7
POST /oauth/token HTTP/1.1
Host: oauth2server.com

code=Yzk5ZDczMzRlNDEwY
&grant_type=code
&client_id=mRkZGFjM
&client_secret=ZGVmMjMz

响应

1
2
3
4
5
6
7
8
9
10
11
12
13
HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
Cache-Control: no-store
Pragma: no-cache

{
"access_token":"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk",
"scope":"create",
"state":"12345678"
}

异常

1
2
3
4
5
6
7
8
9
10
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache

{
"error": "invalid_request",
"error_description": "Request was missing the 'redirect_uri' parameter.",
"error_uri": "See the full API docs at http://oauth2server.com/docs/access_token"
}

Implicit Grant

browser-base

请求

1
https://oauth2server.com/oauth/authorize?response_type=token&client_id=mRkZGFjM&state=TY2OTZhZGFk

响应

1
https://oauth2client.com/cb#token=Yzk5ZDczMzRlNDEwY&state=TY2OTZhZGFk

mobile and native app

请求

1
https://www.arcgis.com/sharing/oauth2/authorize?client_id=eKNjzFFjH9A1ysYd&response_type=token&redirect_uri=exampleapp://auth

响应

1
oauthdemo://auth#access_token=lS0KgilpRsT07qT_iMOg9bBSaWqODC1g061nSLsa8gV2GYtyynB6A-abCsWrDTvN9p7rI0kWa4u-ORXuFUQ7QGxiiniwpCSIV1AqzoLRHF1hYcI4joeDPOzZa9PZigiudtefciZy5&expires_in=7199&username=aaronpk

Paasword Grant

请求

1
2
3
4
5
6
7
8
POST /oauth/token HTTP/1.1
Host: oauth2server.com

grant_type=password
&username=user@example.com
&password=1234luggage
&client_id=xxxxxxxxxx
&client_secret=xxxxxxxxxx

Client Credentials

概述

1
访问自身资源,不代表用户行为

请求

1
2
3
4
5
6
POST /oauth/token HTTP/1.1
Host: oauth2server.com

grant_type=client_credentials
&client_id=xxxxxxxxxx
&client_secret=xxxxxxxxxx

refresh token

注意

1
如果包含scope,需与上一次的scope相同

请求

1
2
3
4
5
6
7
POST /oauth/token HTTP/1.1
Host: oauth2server.com

grant_type=refresh_token
&refresh_token=xxxxxxxxxxx
&client_id=xxxxxxxxxx
&client_secret=xxxxxxxxxx
作者

苏同

发布于

2017-03-20

更新于

2017-03-20

许可协议