-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathget_token.py
78 lines (58 loc) · 2.39 KB
/
get_token.py
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
78
from msal import ConfidentialClientApplication, SerializableTokenCache
import config
import http.server
import os
import sys
import threading
import urllib.parse
import webbrowser
redirect_uri = "http://localhost:8745/"
# We use the cache to extract the refresh token
cache = SerializableTokenCache()
app = ConfidentialClientApplication(config.ClientId, client_credential=config.ClientSecret, token_cache=cache, authority=config.Authority)
url = app.get_authorization_request_url(config.Scopes, redirect_uri=redirect_uri)
# webbrowser.open may fail silently
print("Navigate to the following url in a web browser, if doesn't open automatically:")
print(url)
try:
webbrowser.open(url)
except Exception:
pass
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
parsed_url = urllib.parse.urlparse(self.path)
parsed_query = urllib.parse.parse_qs(parsed_url.query)
global code
code = next(iter(parsed_query['code']), '')
response_body = b'Success. Look back at your terminal.\r\n'
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', len(response_body))
self.end_headers()
self.wfile.write(response_body)
global httpd
t = threading.Thread(target=lambda: httpd.shutdown())
t.start()
code = ''
server_address = ('', 8745)
httpd = http.server.HTTPServer(server_address, Handler)
# If we are running over ssh then the browser on the local machine
# would never be able access localhost:8745
if not os.getenv('SSH_CONNECTION'):
httpd.serve_forever()
if code == '':
print('After login, you will be redirected to a blank (or error) page with a url containing an access code. Paste the url below.')
resp = input('Response url: ')
i = resp.find('code') + 5
code = resp[i : resp.find('&', i)] if i > 4 else resp
token = app.acquire_token_by_authorization_code(code, config.Scopes, redirect_uri=redirect_uri)
print()
if 'error' in token:
print(token)
sys.exit("Failed to get access token")
with open(config.RefreshTokenFileName, 'w') as f:
print(f'Refresh token acquired, writing to file {config.RefreshTokenFileName}')
f.write(token['refresh_token'])
with open(config.AccessTokenFileName, 'w') as f:
print(f'Access token acquired, writing to file {config.AccessTokenFileName}')
f.write(token['access_token'])