def test_verify_id_token_with_certs_uri_fails(self): jwt = self._create_signed_jwt() test_email = 'some_audience_address@testing.gserviceaccount.com' http = HttpMockSequence([ ({'status': '404'}, datafile('certs.json')), ]) with self.assertRaises(VerifyJwtTokenError): verify_id_token(jwt, test_email, http=http)
def test_verify_id_token_with_certs_uri_fails(self): jwt = self._create_signed_jwt() test_email = 'some_audience_address@testing.gserviceaccount.com' http = http_mock.HttpMock( headers={'status': http_client.NOT_FOUND}, data=datafile('certs.json')) with self.assertRaises(client.VerifyJwtTokenError): client.verify_id_token(jwt, test_email, http=http) # Verify mocks. self._verify_http_mock(http)
def resolve_google_oauth(request): # token should be passed as an object {'ID_Token' : id_token } # to this view token = request.data.get('ID_Token') CLIENT_ID = os.environ.get('CLIENT_ID') token.replace(" ", "") try: idinfo = client.verify_id_token(token, CLIENT_ID) if 'hd' not in idinfo: raise AuthenticationFailed('Sorry, only Andelans can sign in') if idinfo['hd'] != 'andela.com': raise AuthenticationFailed('Sorry, only Andelans can sign in') if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise PermissionDenied('Wrong Issuer') if idinfo['email_verified'] == 'True' and idinfo['aud'] == CLIENT_ID: return idinfo except crypt.AppIdentityError: raise PermissionDenied('Invalid Token') return idinfo
def googleOAuthTokenVerify(): # authenticate with Google for Icahn accounts '''from https://developers.google.com/identity/sign-in/web/backend-auth''' token = request.values.get('idtoken', None) try: idinfo = gauthclient.verify_id_token(token, vm_client_id) # If multiple clients access the backend server: if idinfo['aud'] not in [vm_client_id]: raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") except crypt.AppIdentityError: # Invalid token sys.stderr.write("Bad token from client.\n") return None # okay, now we're logged in. yay! userid = idinfo['sub'] useremail = idinfo['email'] sys.stderr.write("Token sign in user: " + ", ".join([useremail, userid]) + "\n") user = User.query.get(useremail) if user: # if user has been here before user.authenticated=True # log them in in DB db_session.add(user) db_session.commit() flask_login.login_user(user, remember=True) # log them in in their browser else: if ('@icahn.mssm.edu' not in useremail) & ('@mssm.edu' not in useremail): # not ISMMS account return 'Unauthorized e-mail address. You must be a MSSM affiliate with an @icahn.mssm.edu or @mssm.edu address!' else: user = User(email = useremail, google_token=userid) # create new user in DB user.authenticated=True # log them in in DB db_session.add(user) db_session.commit() flask_login.login_user(user, remember=False) # log them in in their browser return useremail # return logged in email to user
def check_user(token): try: idinfo = client.verify_id_token(token, CLIENT_ID) return True except crypt.AppIdentityError as e: print e return False
def oauth2callback(request): if request.GET.get('state') != unicode(csrf(request)['csrf_token']): payload = { 'error': 'CSRF token verification failed. Your CSRF token is not valid' } return redirect('results?' + urllib.urlencode(payload)) endpoints = requests.get('https://accounts.google.com/.well-known/openid-configuration').json() payload = { 'code': request.GET.get('code'), 'client_id': config.GOOGLE.get('clientID'), 'client_secret': config.GOOGLE.get('clientSecret'), 'response_type': 'code', 'scope': 'openid email', 'redirect_uri': config.HOST + '/google_login/oauth2callback', 'grant_type': 'authorization_code' } r = requests.post(endpoints.get('token_endpoint'), data=payload) id_token = r.json().get('id_token') user_data = verify_id_token(id_token, config.GOOGLE.get('clientID')) user = get_or_create_user(user_data) if user is None: payload = { 'error': 'Error creating user' } return redirect('results?' + urllib.urlencode(payload)) else: login(request, user) return redirect(results)
def google_info_from_token(token): idinfo = client.verify_id_token(token, settings.GOOGLE_CLIENT_ID) if idinfo['aud'] != settings.GOOGLE_CLIENT_ID: raise crypt.AppIdentityError('aud dont match') if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") return idinfo
def verify_id_token(self, token): idinfo = client.verify_id_token(token, self.client_id) if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise AuthenticationError("Wrong issuer.") return idinfo['email']
def verify_google_token(): token = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjgwNDhmNDQ3YzVjNmRiZGI4ODIwOTYyOTJmYTFiNzk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_id_here.apps.googleusercontent.com' ANDROID_CLIENT_ID = 'insert_android_client_id_here.apps.googleusercontent.com' WEB_CLIENT_ID = 'insert_web_client_id_here.apps.googleusercontent.com' if cache.get(token) != None: print 'From cache:', cache.get(token) # print 'time:', cache.get(token)['exp'], current_milli_time() return 'From cache:\n ' + ', '.join("%s=%r" % (key,val) for (key,val) in cache.get(token).iteritems()) else: # (Receive token by HTTPS POST) try: idinfo = client.verify_id_token(token, CLIENT_ID) # If multiple clients access the backend server: if idinfo['aud'] not in [ANDROID_CLIENT_ID, WEB_CLIENT_ID]: raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") userid = idinfo['sub'] cache.set(token, idinfo, idinfo['exp'] - current_milli_time()) print 'Not from cache', idinfo return 'Not from cache:\n ' + ', '.join("%s=%r" % (key,val) for (key,val) in idinfo.iteritems()) except crypt.AppIdentityError: # Invalid token print 'Invalid Token' return 'Invalid Token'
def verify_admin(): if DEBUG: return token = request.cookies.get('starbook-token') or (request.json and request.json.pop('starbook-token')) google_email = client.verify_id_token(token, CLIENT_ID)['email'] if google_email not in ADMINS: return jsonify({'error': 'You are not allowed to do that'}), 403
def login(request, access_token): """ Validate a google access token and retrieve user's email. Returns ------- user : str User email. permissions : list List of permissions that the user has. """ try: idinfo = client.verify_id_token(access_token, request.registry.GOOGLE_WEB_CLIENT_ID) if idinfo['aud'] not in [request.registry.GOOGLE_WEB_CLIENT_ID]: raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") except crypt.AppIdentityError as e: return request.error('token', e.message, 400) email = idinfo.get('email') if email is None: return request.error('google_data', "Could not find Google email") request.response.headers.extend(remember(request, email)) return { 'user': email, 'permissions': request.user_principals(email), }
def post(self): data = json.loads(self.request.body) user_type = self.get_argument('user_type') if 'access_token' in data: try: details = client.verify_id_token( data['access_token'], config.GOOGLE_OAUTH2_CLIENT_ID ) user = handle_user_authentication( self.dbsession, details, user_type ) self.session['user_type'] = user_type if user_type == 'admin': self.session['buid'] = user.id self.session['admin'] = "true" elif user_type in ('service_provider', 'service_user'): self.session['buid'] = user.user_id self.session['uid'] = user.id self.send_model_response(user) except crypt.AppIdentityError: self.set_status(403) else: self.set_status(400)
def gauth(): # The POST should include `id_token` id_token = request.form.get('id_token', '')[:3072] # Verify the `id_token` using API Client Library idinfo = client.verify_id_token(id_token, CLIENT_ID) # Additional verification: See if `iss` matches Google issuer string if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: return make_response('Authentication failed', 401) id = idinfo['sub'] # For now, we'll always store profile data after successfully # verifying the token and consider the user authenticated. store = CredentialStore.get_by_id(id) if store is None: store = CredentialStore(id=id) # Construct a profile object store.profile = { 'id': id, 'imageUrl': idinfo.get('picture', None), 'name': idinfo.get('name', None), 'email': idinfo.get('email', None) } store.put() session['id'] = id # Not making a session for demo purpose/simplicity return make_response('Authenticated', 200)
def authenticating(request): #connect to our local mongodb print "About to Authenticate user" if request.method == 'GET': #get our collection print "Inside GET" return HttpResponse("OK") elif request.method == 'POST': #get data from the request and insert the record print "Inside POST" print request.body print "PRINTED PAYLOAD" received_json_data=json.loads(request.body) token = received_json_data.get("token",False) print token CLIENT_ID = "979314773329-m6j6e9la8u2o9rt15q8655uqnuuolko5.apps.googleusercontent.com" ANDROID_CLIENT_ID = "979314773329-e7kl7cavu9e85hclbbfscruhmtb4t685.apps.googleusercontent.com" IOS_CLIENT_ID = ' ' WEB_CLIENT_ID = ' ' try: idinfo = client.verify_id_token(token, CLIENT_ID) if idinfo['aud'] not in [ANDROID_CLIENT_ID, IOS_CLIENT_ID, WEB_CLIENT_ID]: raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") if idinfo['hd'] != APPS_DOMAIN_NAME: raise crypt.AppIdentityError("Wrong hosted domain.") except crypt.AppIdentityError: traceback.print_exc() # Invalid token print "Returning Failure of user auth" return HttpResponse("ERROR") userid = idinfo['sub'] print "Returning Success of user auth" return HttpResponse(userid)
def gSignin(): token = request.data try: idinfo = client.verify_id_token(token, CLIENT_ID) if idinfo['aud'] not in [WEB_CLIENT_ID]: raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") except crypt.AppIdentityError: return json.dumps('No se pudo ingresar al sistema') userid = idinfo['sub'] user = sess.query(User).filter(User.guid == userid).first() if user != None: session['user_id'] = user.id session['guid'] = user.guid session['gfolder'] = user.gfolder flash('Bienvenido %s' % user.name) return json.dumps("%s" % user.name) else: session['error'] = "eroor" return redirect(url_for('auth.signin'))
def SecurityCheck(self, func, request, *args, **kwargs): """Check if access should be allowed for the request.""" try: auth_header = request.headers.get("Authorization", "") if not auth_header.startswith(self.BEARER_PREFIX): raise crypt.AppIdentityError("JWT token is missing.") token = auth_header[len(self.BEARER_PREFIX):] auth_domain = config_lib.CONFIG["AdminUI.firebase_auth_domain"] project_id = auth_domain.split(".")[0] idinfo = client.verify_id_token(token, project_id, cert_uri=self.CERT_URI) if idinfo["iss"] != self.SECURE_TOKEN_PREFIX + project_id: raise crypt.AppIdentityError("Wrong issuer.") request.user = idinfo["email"] except crypt.AppIdentityError as e: # For a homepage, just do a pass-through, otherwise JS code responsible # for the Firebase auth won't ever get executed. This approach is safe, # because wsgiapp.HttpRequest object will raise on any attempt to # access uninitialized HttpRequest.user attribute. if request.path != "/": return self.AuthError("JWT token validation failed: %s" % e) return func(request, *args, **kwargs)
def process_request(self, request): # do not affect the admin api requests if request.get_full_path().startswith('/admin'): return None try: google_sign_in_token = request.META['HTTP_' + GOOGLE_SIGN_IN_TOKEN_HEADER] # verify the google id token user_info = client.verify_id_token(google_sign_in_token, GOOGLE_OAUTH_WEB_CLIENT_ID) if user_info['aud'] != GOOGLE_OAUTH_WEB_CLIENT_ID: raise crypt.AppIdentityError("unrecognized client") if user_info['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("wrong issuer") email = user_info['email'] if not email: return self.unauthorize() request.META['jrn-email'] = email # for all apis, except user creation, verify the requested user exists in db if not request.get_full_path().startswith('/users') or request.method != 'POST': user = User.objects.filter(email=email) if user: request.META['jrn-user-id'] = user[0].user_id else: return self.unauthorize() return None # return None to continue with middleware and handling the request except Exception as e: return self.unauthorize()
def get_info_from_google(token = None): try: if session['signin_party'] != 'google': print 'login_required: Do not verified by Google.' return False, {} except KeyError: print 'login_required: signin_party is missed.' return False, {} if token == None: try: token = session['token'] except KeyError: print 'login_required: token is missed.' return False, {} try: idinfo = client.verify_id_token(token, config.CLIENT_ID) # If multiple clients access the backend server: #if idinfo['aud'] not in [ANDROID_CLIENT_ID, IOS_CLIENT_ID, WEB_CLIENT_ID]: # raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") #if idinfo['hd'] != APPS_DOMAIN_NAME: # raise crypt.AppIdentityError("Wrong hosted domain.") except crypt.AppIdentityError as e: # Invalid token print e return False, {} return True, idinfo
def login_google_callback(request): url = "https://www.googleapis.com/oauth2/v3/token?code=" url += request.GET.get("code") url += "&client_id=" url += settings.GA_CLIENT_ID url += "&client_secret=" url += settings.GA_CLIENT_SECRET url += "&redirect_uri=" url += request.build_absolute_uri(reverse("login_google_callback")) url += "&grant_type=authorization_code" r = requests.post(url) jwt = verify_id_token(r.json().get("id_token"), settings.GA_CLIENT_ID) email = jwt.get("email").lower() try: user = User.objects.get(email=email) except User.DoesNotExist: user = User(email=email) user.save() user.backend = "django.contrib.auth.backends.ModelBackend" try: connection = UserConnection.objects.get(token=request.GET.get("state"), user__isnull=True) except UserConnection.DoesNotExist: return redirect("home") manual_login(request, user) connection.user = user connection.save() if connection.referrer_path: return redirect(connection.referrer_path) return redirect("home")
def google_auth(self, request): data = request.data if 'auth_token' not in data: return Response(status=status.HTTP_400_BAD_REQUEST) try: idinfo = client.verify_id_token(data['auth_token'], '92340928633-a2lv6k929j34994pjcfmpdm9a8kc9lme.apps.googleusercontent.com') # If multiple clients access the backend server: # if idinfo['aud'] not in [ANDROID_CLIENT_ID, IOS_CLIENT_ID, WEB_CLIENT_ID]: # raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") # if idinfo['hd'] != APPS_DOMAIN_NAME: # raise crypt.AppIdentityError("Wrong hosted domain.") except crypt.AppIdentityError as e: print e # Invalid token userid = idinfo['sub'] if User.objects.filter(google_auth_id=userid).exists(): user = User.objects.filter(google_auth_id=userid).get() user.save() else: serializer = self.get_serializer(data={'google_auth_id': userid, 'email': idinfo['email']}) # try: serializer.is_valid(raise_exception=True) # except ValidationError as e: # print e user = serializer.save() serializer = UserSerializer(user) return Response(serializer.data,status=200)
def fetch_info_from_login_token(token): google_api_shmidusic_project_id = "521166378127-6hmr4e9rspkj2amipftmkt4qukb1ljr4.apps.googleusercontent.com" try: user_info = client.verify_id_token(token, google_api_shmidusic_project_id) return user_info except crypt.AppIdentityError as exc: # log maybe? return None
def test_verify_id_token_with_certs_uri(self): jwt = self._create_signed_jwt() http = HttpMockSequence([({"status": "200"}, datafile("certs.json"))]) contents = verify_id_token(jwt, "some_audience_address@testing.gserviceaccount.com", http) self.assertEqual("billy bob", contents["user"]) self.assertEqual("data", contents["metadata"]["meta"])
def verify(): id_token = request.headers.get('Authorization') if not id_token: abort(400) try: jwt = verify_id_token(id_token, app.config.get('GOOGLE_ID')) return jsonify(jwt) except AppIdentityError as e: print "error", e abort(403)
def verify_email_from_request(): if DEBUG: return token = request.cookies.get('starbook-token') or (request.json and request.json.pop('starbook-token')) google_email = client.verify_id_token(token, CLIENT_ID)['email'] request_email = request.json.get(PERSON_UNIQUE_KEY, None) if request_email is None: return if request_email != google_email and google_email not in ADMINS: return jsonify({'error': 'You are not allowed to do that'}), 403
def signIn(): data = request.get_json() provider_user = {} if(data["provider"] == "google"): provider_user = client.verify_id_token(data['id'], '1058234090303-derenhna8oi3h32bf47j77rqtrfalrcd.apps.googleusercontent.com') user = User(name="<name>", provider="google", provider_id=provider_user['sub']) create_user_if_needed(user) return jsonify(provider_user)
def test_verify_id_token_with_certs_uri(self): jwt = self._create_signed_jwt() http = HttpMockSequence([ ({'status': '200'}, datafile('certs.json')), ]) contents = verify_id_token(jwt, 'some_audience_address@testing.gserviceaccount.com', http=http) self.assertEqual('billy bob', contents['user']) self.assertEqual('data', contents['metadata']['meta'])
def verify(self, id_token): try: idinfo = client.verify_id_token(id_token, self._client_id) # If multiple clients access the backend server: if idinfo['aud'] not in self._client_ids: raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") except crypt.AppIdentityError: return (False, None) return (True, idinfo)
def get(self): user_type = self.get_argument('user_type', None) next_url = self.get_argument('next', None) if next_url: self.session['next'] = next_url #self.set_secure_cookie('next', next_url) if user_type: self.session['user_type'] = user_type #self.set_secure_cookie('user_type', user_type) if self.get_argument('code', False): user = yield self.get_authenticated_user( redirect_uri=self.REDIRECT_URL, code=self.get_argument('code')) try: details = client.verify_id_token( user['id_token'], config.GOOGLE_OAUTH2_CLIENT_ID ) user_type = self.session['user_type'] user = handle_user_authentication( self.dbsession, details, user_type ) #self.session['user_type'] = user_type if user_type == 'admin': self.session['buid'] = user.id self.session['uid'] = user.id self.session['admin'] = "true" elif user_type in ('service_provider', 'service_user'): self.session['buid'] = user.user_id self.session['uid'] = user.id next_url = self.session['next'] if next_url: self.redirect(next_url) else: self.send_model_response(user) except crypt.AppIdentityError: self.set_status(403) except AppException: self.set_status(400) self.write('User is not admin') else: yield self.authorize_redirect( redirect_uri=self.REDIRECT_URL, client_id=self.settings['google_oauth']['key'], scope=['email', 'profile'], response_type='code', extra_params={'approval_prompt': 'auto'})
def getIdInfo(token): try: idinfo = client.verify_id_token(token, CLIENT_ID) if idinfo['aud'] not in [CLIENT_ID]: # raise crypt.AppIdentityError("Unrecognized client.") return None if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: # raise crypt.AppIdentityError("Wrong issuer.") return None except crypt.AppIdentityError: return None return idinfo
def request_google_auth_service(client_id, token): idinfo = client.verify_id_token(token, client_id) if idinfo['aud'] not in GOOGLE_ACCEPT_CLIENT_IDS: raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") idinfo['uid'] = idinfo['sub'] for (x, y) in (('name', 'username'), ('given_name', 'first_name'), ('family_name', 'last_name')): idinfo[y] = idinfo[x] if x in idinfo else '' idinfo['provider'] = 'google-oauth2' logger.debug('idinfo = {}'.format(idinfo)) return idinfo