如何使用curl直接获取Google OAuth 2.0访问令牌?(不使用Google库)

26

我正在尝试按照这个教程使用Google的OAuth 2.0 API进行身份验证。但是,我想直接使用curl命令而不是使用他们的库。

我已经获得了我的客户端ID和客户端秘钥。现在我正在尝试获取访问令牌,像这样:

curl \
--request POST \
--header "Content-Type: application/json" \
--data '{
  "client_id":"MY_CLIENT_ID",
  "client_secret":"MY_SECRET_KEY",
  "redirect_uri": "http://localhost/etc",
  "grant_type":"authorization_code"
}' \
"https://accounts.google.com/o/oauth2/token"

然而,它没有起作用。它给了我以下错误:

{
  "error" : "invalid_request",
  "error_description" : "Required parameter is missing: grant_type"
}

请问能否提供一个获取访问令牌(和刷新令牌)的curl调用示例?


2
请查看:https://dev59.com/JmMl5IYBdhLWcg3woYTa#18260206 - Jay Lee
3个回答

17

你提供的数据应该是表单编码而不是JSON对象,并且在"code"参数中还应该提供授权码值。例如:

curl -d "client_id=MY_CLIENT_ID&\
  client_secret=MY_SECRET_KEY&\
  redirect_uri=http://localhost/etc&\
  grant_type=authorization_code&\
  code=CODE" https://oauth2.googleapis.com/token

这是一个GET请求还是POST请求? - Saqib Ali
1
使用 -d 会自动将其转换为 POST 并设置所需的内容类型。 - Hans Z.
这种技术能否扩展到涵盖双腿OAuth2? - Wheezil
1
代码参数来自原始的身份验证请求:https://developers.google.com/android-publisher/authorization - Tad
什么是“代码”?我应该从哪里获取它? - undefined

8

-1
create and execute a python script file to obtain JWT assertion key which will be further used in curl command :

python script for generating jwt assertion key :
import jwt
import os
import json
import sys

# Load the service account key JSON
service_account_key = json.loads(open("name of your service account key file").read())

# Extract necessary information from the service account key JSON
client_email = service_account_key["client_email"]



# Create the payload with necessary claims
payload = {
    "iss": client_email,
    "sub": client_email,
    "aud": "https://oauth2.googleapis.com/token",
    "exp": expired timestamp,  # Replace with the expiration timestamp
    "iat": current timestamp,  # Replace with the issuance timestamp
    "scope": "https://www.googleapis.com/auth/cloud-platform"
}

# Sign the payload with the service account's private key
#with open(os.path.join(sys.path[0], 'privatekey.pem'), "r") as private_key_file:
#    private_key = private_key_file.read()

private_key = "mention your private key present in service account key file"

jwt_assertion = jwt.encode(payload, private_key, algorithm="RS256")


print(jwt_assertion)


______________________________________________________________________

assertion key will be obtained after executing the above python script , paste that in below curl command ,

Now, curl -X POST "https://oauth2.googleapis.com/token" \
     -d "scope=read&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" \
     -d "assertion=(your jwt_assertion key)"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接