-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGoogle-Authentication.py
416 lines (333 loc) · 12.6 KB
/
Google-Authentication.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
from typing import Optional
from datetime import datetime, timedelta
import jwt
# from jwt import PyJWTError
from fastapi import Depends, FastAPI, HTTPException
from fastapi.encoders import jsonable_encoder
from fastapi.security.oauth2 import (
OAuth2,
OAuthFlowsModel,
get_authorization_scheme_param,
)
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
import uvicorn
from starlette.status import HTTP_403_FORBIDDEN
from starlette.responses import RedirectResponse, JSONResponse, HTMLResponse
from starlette.requests import Request
from pydantic import BaseModel
import httplib2
from oauth2client import client
from google.oauth2 import id_token
from google.auth.transport import requests
import nest_asyncio
from pyngrok import ngrok
from fastapi.middleware.cors import CORSMiddleware
COOKIE_AUTHORIZATION_NAME = "Authorization"
COOKIE_DOMAIN = "localhost"
PROTOCOL = "http://"
FULL_HOST_NAME = "localhost"
PORT_NUMBER = 8000
CLIENT_ID = "525768242152-g77ejmcbgiftl7d8c3gto3uhse508epe.apps.googleusercontent.com"
CLIENT_SECRETS_JSON = "client_secret_525768242152-g77ejmcbgiftl7d8c3gto3uhse508epe.apps.googleusercontent.com.json"
API_LOCATION = f"{PROTOCOL}{FULL_HOST_NAME}:{PORT_NUMBER}"
SWAP_TOKEN_ENDPOINT = "/swap_token"
SUCCESS_ROUTE = "/users/me"
ERROR_ROUTE = "/login_error"
SECRET_KEY = "hAatS3lN84DqX4IM2hFqFCir"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "[email protected]",
"disabled": False,
}
}
google_login_javascript_client = f"""<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Article">
<head>
<meta charset="UTF-8">
<meta name="google-signin-client_id" content="{CLIENT_ID}">
<title>Google Login</title><script src="https://apis.google.com/js/platform.js" async defer></script>
<body>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<script>function onSignIn(googleUser) {{
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', '{API_LOCATION}{SWAP_TOKEN_ENDPOINT}');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('X-Google-OAuth2-Type', 'client');
xhr.onload = function() {{
console.log('Signed in as: ' + xhr.responseText);
}};
xhr.send(id_token);
}}</script>
<div><br></div>
<a href="#" onclick="signOut();">Sign out</a>
<script>
function signOut() {{
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {{
console.log('User signed out.');
}});
}}
</script>
</body>
</html>"""
google_login_javascript_server = f"""<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Article">
<head>
<meta charset="UTF-8">
<title>Google Login</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
</script>
<script>
function start() {{
gapi.load('auth2', function() {{
auth2 = gapi.auth2.init({{
client_id: '{CLIENT_ID}',
// Scopes to request in addition to 'profile' and 'email'
// scope: 'additional_scope'
}});
}});
}}
</script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
<script>
$('#signinButton').click(function() {{
// signInCallback defined in step 6.
auth2.grantOfflineAccess().then(signInCallback);
}});
</script>
<script>
function signInCallback(authResult) {{
if (authResult['code']) {{
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({{
type: 'POST',
url: '{API_LOCATION}{SWAP_TOKEN_ENDPOINT}',
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {{
'X-Requested-With': 'XMLHttpRequest',
'X-Google-OAuth2-Type': 'server'
}},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {{
location.href = '{API_LOCATION}{SUCCESS_ROUTE}'
// Handle or verify the server response.
}},
processData: false,
data: authResult['code']
}});
}} else {{
// There was an error.
console.log(e)
location.href = '{API_LOCATION}{ERROR_ROUTE}'
}}
}}
</script>
</body>
</html>"""
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: str = None
email: str = None
class User(BaseModel):
username: str
email: str = None
full_name: str = None
disabled: bool = None
class OAuth2PasswordBearerCookie(OAuth2):
def __init__(
self,
tokenUrl: str,
scheme_name: str = None,
scopes: dict = None,
auto_error: bool = True,
):
if not scopes:
scopes = {}
flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": scopes})
super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)
async def __call__(self, request: Request) -> Optional[str]:
header_authorization: str = request.headers.get("Authorization")
cookie_authorization: str = request.cookies.get("Authorization")
header_scheme, header_param = get_authorization_scheme_param(
header_authorization
)
cookie_scheme, cookie_param = get_authorization_scheme_param(
cookie_authorization
)
if header_scheme.lower() == "bearer":
authorization = True
scheme = header_scheme
param = header_param
elif cookie_scheme.lower() == "bearer":
authorization = True
scheme = cookie_scheme
param = cookie_param
else:
authorization = False
if not authorization or scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
)
else:
return None
return param
oauth2_scheme = OAuth2PasswordBearerCookie(tokenUrl="/token")
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
def get_user_by_email(db, email: str):
for username, value in db.items():
if value.get("email") == email:
user_dict = db[username]
return User(**user_dict)
def authenticate_user_email(fake_db, email: str):
user = get_user_by_email(fake_db, email)
if not user:
return False
return user
def create_access_token(*, data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str = payload.get("sub")
if email is None:
raise credentials_exception
token_data = TokenData(email=email)
except PyJWTError:
raise credentials_exception
user = get_user_by_email(fake_users_db, email=token_data.email)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(current_user: User = Depends(get_current_user)):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
@app.get("/google_login_client", tags=["security"])
def google_login_client():
return HTMLResponse(google_login_javascript_client)
@app.get("/google_login_server", tags=["security"])
def google_login_server():
return HTMLResponse(google_login_javascript_server)
@app.post(f"{SWAP_TOKEN_ENDPOINT}", response_model=Token, tags=["security"])
async def swap_token(request: Request = None):
if not request.headers.get("X-Requested-With"):
raise HTTPException(status_code=400, detail="Incorrect headers")
google_client_type = request.headers.get("X-Google-OAuth2-Type")
if google_client_type == 'server':
try:
body_bytes = await request.body()
auth_code = jsonable_encoder(body_bytes)
credentials = client.credentials_from_clientsecrets_and_code(
CLIENT_SECRETS_JSON, ["profile", "email"], auth_code
)
http_auth = credentials.authorize(httplib2.Http())
email = credentials.id_token["email"]
except:
raise HTTPException(status_code=400, detail="Unable to validate social login")
if google_client_type == 'client':
body_bytes = await request.body()
auth_code = jsonable_encoder(body_bytes)
try:
idinfo = id_token.verify_oauth2_token(auth_code, requests.Request(), CLIENT_ID)
# Or, if multiple clients access the backend server:
# idinfo = id_token.verify_oauth2_token(token, requests.Request())
# if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
# raise ValueError('Could not verify audience.')
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
# If auth request is from a G Suite domain:
# if idinfo['hd'] != GSUITE_DOMAIN_NAME:
# raise ValueError('Wrong hosted domain.')
if idinfo['email'] and idinfo['email_verified']:
email = idinfo.get('email')
else:
raise HTTPException(status_code=400, detail="Unable to validate social login")
except:
raise HTTPException(status_code=400, detail="Unable to validate social login")
authenticated_user = authenticate_user_email(fake_users_db, email)
if not authenticated_user:
raise HTTPException(status_code=400, detail="Incorrect email address")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": authenticated_user.email}, expires_delta=access_token_expires
)
token = jsonable_encoder(access_token)
response = JSONResponse({"access_token": token, "token_type": "bearer"})
response.set_cookie(
COOKIE_AUTHORIZATION_NAME,
value=f"Bearer {token}",
domain=COOKIE_DOMAIN,
httponly=True,
max_age=1800,
expires=1800,
)
return response
@app.get("/")
async def homepage():
return "Welcome to the security test!"
@app.get(f"{ERROR_ROUTE}", tags=["security"])
async def login_error():
return "Something went wrong logging in!"
@app.get("/logout", tags=["security"])
async def route_logout_and_remove_cookie():
response = RedirectResponse(url="/")
response.delete_cookie(COOKIE_AUTHORIZATION_NAME, domain=COOKIE_DOMAIN)
return response
@app.get("/openapi.json", tags=["documentation"])
async def get_open_api_endpoint(current_user: User = Depends(get_current_active_user)):
response = JSONResponse(
get_openapi(title="FastAPI security test", version=1, routes=app.routes)
)
return response
@app.get("/documentation", tags=["documentation"])
async def get_documentation(current_user: User = Depends(get_current_active_user)):
response = get_swagger_ui_html(openapi_url="/openapi.json", title="docs")
return response
@app.get("/secure_endpoint", tags=["security"])
async def get_open_api_endpoint(current_user: User = Depends(get_current_active_user)):
response = "How cool is this?"
return response
@app.get("/users/me/", response_model=User, tags=["users"])
async def read_users_me(current_user: User = Depends(get_current_active_user)):
return current_user
@app.get("/users/me/items/", tags=["users"])
async def read_own_items(current_user: User = Depends(get_current_active_user)):
return [{"item_id": "Foo", "owner": current_user.username}]
ngrok_tunnel = ngrok.connect(8000)
print('Public URL:', ngrok_tunnel.public_url)
nest_asyncio.apply()
uvicorn.run(app, port=8000)