-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexchange_code_for_token_example.py
More file actions
77 lines (62 loc) · 2.26 KB
/
exchange_code_for_token_example.py
File metadata and controls
77 lines (62 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import argparse
import requests
import json
def exchange_code_for_token(
code: str,
code_verifier: str,
client_id: str,
client_secret: str,
redirect_uri: str,
) -> dict[str, str]:
"""
Exchange the authorization code for an access token.
Args:
code (str): The authorization code received from Snyk after user authorization.
code_verifier (str): The code verifier used in the PKCE flow.
client_id (str): The client ID for the Snyk app.
client_secret (str): The client secret for the Snyk app.
redirect_uri (str): The redirect URI for the Snyk app.
Returns:
dict: The response containing the access token and other details.
"""
url: str = "https://api.snyk.io/oauth2/token"
data: dict = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_uri,
"client_id": client_id,
"client_secret": client_secret,
"code_verifier": code_verifier,
}
headers: dict = {"Content-Type": "application/x-www-form-urlencoded"}
resp: requests.Response = requests.post(url, data=data, headers=headers)
resp.raise_for_status()
return resp.json()
def main():
parser: argparse.ArgumentParser = argparse.ArgumentParser(
description="Exchange Snyk OAuth2 authorization code for an access token."
)
parser.add_argument(
"--code", required=True, help="Authorization code from Snyk OAuth2 callback"
)
parser.add_argument(
"--code-verifier",
required=True,
help="PKCE code verifier used in the OAuth2 flow",
)
parser.add_argument("--client-id", required=True, help="Snyk App client ID")
parser.add_argument("--client-secret", required=True, help="Snyk App client secret")
parser.add_argument(
"--redirect-uri", required=True, help="Redirect URI used in the OAuth2 flow"
)
args: argparse.Namespace = parser.parse_args()
token_response: dict[str, str] = exchange_code_for_token(
code=args.code,
code_verifier=args.code_verifier,
client_id=args.client_id,
client_secret=args.client_secret,
redirect_uri=args.redirect_uri,
)
print(json.dumps(token_response, indent=2))
if __name__ == "__main__":
main()