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

dvtswwa3  于 2023-11-16  发布在  Go
关注(0)|答案(3)|浏览(208)

我尝试按照本教程使用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调用,以获得访问令牌(和刷新令牌)?

g6ll5ycj

g6ll5ycj1#

a)您提供的数据应该是表单编码的,而不是以JSON对象的形式呈现; b)您还应该在“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

字符串

1cklez4t

1cklez4t2#

虽然不直接使用CURL,但您也可以使用Google OAuth Playground获取和测试OAuth令牌:https://developers.google.com/oauthplayground/

j91ykkif

j91ykkif3#

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)"

字符串

相关问题