def login(self): oauth = OAuth2Session(self.client_id, redirect_uri=self.redirect_uri,scope=self.scope) return oauth.authorization_url(self.oauth_auth_url)
def __init__(self, key, secret, base_url, token_url): self.base_url = base_url client = BAC(client_id=key) self.oauth = OAuth2Session(client=client) self.oauth.fetch_token(token_url=base_url + token_url, client_secret=secret, client_id=key)
logger.info("oauth1 request token url is %s", oauth1RequestTokenUrl) logger.info("oauth1 authorize url is %s", oauth1AuthorizeUrl) logger.info("oauth1 access token url is %s", oauth1AccessTokenUrl) oauth2AuthorizeUrl = config['urls']['oauth2']['authorize'].replace( "{0}", environ) oauth2GetTokenUrl = config['urls']['oauth2']['getToken'].replace( "{0}", environ) oauth2Callback = callback logger.info("oauth2 authorize url is %s", oauth2AuthorizeUrl) logger.info("oauth2 get token url is %s", oauth2GetTokenUrl) logger.info("oauth2 callback url is %s", oauth2Callback) oauth2Session = OAuth2Session(clientKey, redirect_uri=oauth2Callback) oauth1Session = OAuth1Session(clientKey, clientSecret) token = None class OAuth2: def getAuthorizeCodeUrl(self): (authUrl, state) = oauth2Session.authorization_url(oauth2AuthorizeUrl) logger.info("authorization url is %s", authUrl) driver.get(authUrl) wait = WebDriverWait(driver, 300).until(EC.url_contains(callback)) codeUrl = driver.current_url
def __get_new_session(self): session = OAuth2Session(client=self.__client) self.__session = OAuth2Session(client=self.__client, token=self.__get_token(session), token_updater=self.__set_token) return
def profile(): """Fetching a protected resource using an OAuth 2 token. """ github = OAuth2Session(client_id, token=session['oauth_token']) return jsonify(github.get('https://api.github.com/user').json())
def session(self): return OAuth2Session( self.client_id, redirect_uri=self.redirect_uri, scope=self.scope, )
app = Flask(__name__) app.config['SECRET_KEY'] = 'SIJFhkdoufoerljdfjto' with open("../cross-inst_config.yml", 'r') as stream: app.app_config = yaml.load(stream) # get a token scope = [ 'WMS_NCIP', 'WMS_Availability', 'SCIM:read_self', 'context:128807', 'refresh_token' ] app.config['auth'] = HTTPBasicAuth(app.app_config.get('key'), app.app_config.get('secret')) app.config['oauth_session'] = OAuth2Session( app.app_config.get('key'), redirect_uri='http://localhost:5000/', scope=scope) @app.before_request def getToken(): if request.args.get('error'): #render error page return "error " + request.args['error'] elif request.args.get('code'): try: token = app.config['oauth_session'].fetch_token( token_url=app.app_config.get('token_url'), authorization_response=request.url, auth=app.config.get('auth')) # redirect
import webbrowser, facebook from requests_oauthlib import OAuth2Session from requests_oauthlib.compliance_fixes import facebook_compliance_fix # Credentials you get from registering a new application client_id = '1387733244617941' client_secret = '0aebb282152cbca66116bd5707d8b0c5' # OAuth endpoints given in the Facebook API documentation authorization_base_url = 'https://www.facebook.com/dialog/oauth' token_url = 'https://graph.facebook.com/oauth/access_token' redirect_uri = 'http://www.myserver.com/coliw' # Should match Site URL facebook = OAuth2Session(client_id, redirect_uri=redirect_uri) facebook = facebook_compliance_fix(facebook) # Redirect user to Facebook for authorization authorization_url, state = facebook.authorization_url(authorization_base_url) webbrowser.open_new_tab(authorization_url) print(state) # Get the authorization verifier code from the callback url redirect_response = 'https://www.myserver.com/coliw' # # # Fetch the access token #facebook.fetch_token(token_url, client_secret=client_secret, # authorization_response=redirect_response) # Fetch a protected resource, i.e. user profile r = facebook.get('https://graph.facebook.com/me?') print(r.content)
def index(): ttam_oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scopes) auth_url, state = ttam_oauth.authorization_url(API_AUTH_URL) return render_template('index.html', auth_url=auth_url)
def google_callback(): # user clicks on cancel if "error" in request.args: flash("please use another sign in method then", "warning") return redirect("/") google = OAuth2Session( GOOGLE_CLIENT_ID, state=session["oauth_state"], scope=_scope, redirect_uri=_redirect_uri, ) token = google.fetch_token( _token_url, client_secret=GOOGLE_CLIENT_SECRET, authorization_response=request.url, ) # Fetch a protected resource, i.e. user profile # { # "email": "*****@*****.**", # "family_name": "First name", # "given_name": "Last name", # "id": "1234", # "locale": "en", # "name": "First Last", # "picture": "http://profile.jpg", # "verified_email": true # } google_user_data = google.get( "https://www.googleapis.com/oauth2/v1/userinfo").json() email = google_user_data["email"] user = User.get_by(email=email) picture_url = google_user_data.get("picture") if user: if picture_url and not user.profile_picture_id: LOG.d("set user profile picture to %s", picture_url) file = create_file_from_url(picture_url) user.profile_picture_id = file.id db.session.commit() # create user else: if not can_be_used_as_personal_email(email): flash( f"You cannot use {email} as your personal inbox.", "error", ) return redirect(url_for("auth.login")) LOG.d("create google user with %s", google_user_data) user = User.create(email=email.lower(), name=google_user_data["name"], activated=True) if picture_url: LOG.d("set user profile picture to %s", picture_url) file = create_file_from_url(picture_url) user.profile_picture_id = file.id db.session.commit() login_user(user) email_utils.send_welcome_email(user.email, user.name) flash(f"Welcome to SimpleLogin {user.name}!", "success") next_url = None # The activation link contains the original page, for ex authorize page if "google_next_url" in session: next_url = session["google_next_url"] LOG.debug("redirect user to %s", next_url) # reset the next_url to avoid user getting redirected at each login :) session.pop("google_next_url", None) return after_login(user, next_url)
def __init__(self, client_id, client_secret): self.session = OAuth2Session(client_id) self.client_secret = client_secret
def _oauth(self): return OAuth2Session(self.client_id, redirect_uri=self.callback_uri, scope=self.scope)
def auth_callback(self, user): """Exchange temporary credentials for permanent credentials This is called in the view that handles the user once they are returned to the OSF after authenticating on the external service. """ # make sure the user has temporary credentials for this provider try: cached_credentials = session.data['oauth_states'][self.short_name] except KeyError: raise PermissionsError("OAuth flow not recognized.") if self._oauth_version == OAUTH1: request_token = request.args.get('oauth_token') # make sure this is the same user that started the flow if cached_credentials.get('token') != request_token: raise PermissionsError("Request token does not match") response = OAuth1Session( client_key=self.client_id, client_secret=self.client_secret, resource_owner_key=cached_credentials.get('token'), resource_owner_secret=cached_credentials.get('secret'), verifier=request.args.get('oauth_verifier'), ).fetch_access_token(self.callback_url) elif self._oauth_version == OAUTH2: state = request.args.get('state') # make sure this is the same user that started the flow if cached_credentials.get('state') != state: raise PermissionsError("Request token does not match") try: response = OAuth2Session( self.client_id, redirect_uri=web_url_for('oauth_callback', service_name=self.short_name, _absolute=True), ).fetch_token( self.callback_url, client_secret=self.client_secret, code=request.args.get('code'), ) except (MissingTokenError, RequestsHTTPError): raise HTTPError(http.SERVICE_UNAVAILABLE) # pre-set as many values as possible for the ``ExternalAccount`` info = self._default_handle_callback(response) # call the hook for subclasses to parse values from the response info.update(self.handle_callback(response)) try: # create a new ``ExternalAccount`` ... self.account = ExternalAccount( provider=self.short_name, provider_id=info['provider_id'], provider_name=self.name, ) self.account.save() except KeyExistsException: # ... or get the old one self.account = ExternalAccount.find_one( Q('provider', 'eq', self.short_name) & Q('provider_id', 'eq', info['provider_id'])) assert self.account is not None # ensure that provider_name is correct self.account.provider_name = self.name # required self.account.oauth_key = info['key'] # only for OAuth1 self.account.oauth_secret = info.get('secret') # only for OAuth2 self.account.expires_at = info.get('expires_at') self.account.refresh_token = info.get('refresh_token') # additional information self.account.display_name = info.get('display_name') self.account.profile_url = info.get('profile_url') self.account.save() # add it to the user's list of ``ExternalAccounts`` if self.account not in user.external_accounts: user.external_accounts.append(self.account) user.save()
def identify(self, token): try: if self.legacy_idm: profile_response = requests.get( self.profile_api_url + '?access_token=%s' % token['access_token'], verify=self.verify_https) else: oauth = OAuth2Session(self.client_id, token=token) profile_response = oauth.get(self.profile_api_url, verify=self.verify_https) except requests.exceptions.SSLError as e: # TODO search a better way to detect invalid certificates if "verify failed" in six.text_type(e): raise InsecureTransportError() else: raise # Token can be invalid if not profile_response.ok: error = profile_response.json() if error.get('error', '') == 'invalid_token': raise ValueError(error.get('error_description')) else: profile_response.raise_for_status() else: user_data = profile_response.json() email = user_data[self.profile_api_mail_field] user_name = user_data[self.profile_api_user_field] # In CKAN can exists more than one user associated with the same email # Some providers, like Google and FIWARE only allows one account per email user = None users = model.User.by_email(email) if len(users) == 1: user = users[0] # If the user does not exist, we have to create it... if user is None: user = model.User(email=email) # Now we update his/her user_name with the one provided by the OAuth2 service # In the future, users will be obtained based on this field user.name = user_name # Update fullname if self.profile_api_fullname_field != "" and self.profile_api_fullname_field in user_data: user.fullname = user_data[self.profile_api_fullname_field] # Update sysadmin status if self.profile_api_groupmembership_field != "" and self.profile_api_groupmembership_field in user_data: user.sysadmin = self.sysadmin_group_name in user_data[ self.profile_api_groupmembership_field] # Hack to let us manage sysadmin rights without even if we can't configure the UM if self.sysadmin_email_domain in email: user.sysadmin = True # Hack to check the info we're getting on each user user.about = user_data.get("discoveryUserBeta", "false") # Save the user in the database model.Session.add(user) model.Session.commit() model.Session.remove() return user.name
def generate_oauth_redirect_url(): oauth = OAuth2Session(settings.DISCORD_APP_ID, redirect_uri=settings.DISCORD_CALLBACK_URL, scope=SCOPES) url, state = oauth.authorization_url(AUTH_URL) return url
def get(self, request, *args, **kwargs): oauth = OAuth2Session(client_id=settings.IDP_CLIENT_ID, redirect_uri=settings.IDP_REDIRECT_URL, scope=settings.IDP_API_SCOPES) auth_url, state = oauth.authorization_url(settings.IDP_AUTHORIZE_URL) return HttpResponseRedirect(auth_url)
from ConfigParser import ConfigParser from oauthlib.oauth2 import BackendApplicationClient from requests_oauthlib import OAuth2Session import time from shapely.geometry import Polygon, Point import json from collections import namedtuple from unidecode import unidecode cfg = ConfigParser() cfg.readfp(open('config/yelp.cfg')) client_id = cfg.get('api', 'app_id') client_secret = cfg.get('api', 'app_secret') client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url="https://api.yelp.com/oauth2/token", client_id=client_id, client_secret=client_secret) base_url = "https://api.yelp.com/v3/businesses/search?" fields = [ 'id', 'lat', 'lon', 'name', 'city', 'address', 'rating', 'price', 'url', 'category1', 'category2', 'category3' ] Restaurant = namedtuple('Restaurant', fields) # # Format's a yelp location dictionary as a readable address
from google.auth.transport import requests app = Flask(__name__) client = datastore.Client() CLIENT_ID = secrets.secretID CLIENT_SECRET = secrets.secret REDIRECT_URL = 'https://randhagufin.appspot.com/userInfo' # These let us get basic info to identify a user and not much else # they are part of the Google People API scope = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid' ] oauth = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URL, scope=scope) @app.route('/') def index(): authorization_url, state = oauth.authorization_url( 'https://accounts.google.com/o/oauth2/auth', # access_type and prompt are Google specific extra # parameters. access_type="offline", prompt="select_account") return render_template('index.html', url=authorization_url) @app.route('/boats', methods=['POST', 'GET']) def boat_get_post():
# Credentials you get from registering a new application client_id = '770jc8r54ghlx3' client_secret = '5B7myRpqsvTv65zf' # OAuth endpoints given in the LinkedIn API documentation authorization_base_url = 'https://www.linkedin.com/uas/oauth2/authorization' token_url = 'https://www.linkedin.com/uas/oauth2/accessToken' from requests_oauthlib import OAuth2Session from requests_oauthlib.compliance_fixes import linkedin_compliance_fix import requests linkedin = OAuth2Session( client_id, redirect_uri='https://www.linkedin.com/developer/apps/5139153/auth') linkedin = linkedin_compliance_fix(linkedin) # # Redirect user to LinkedIn for authorization authorization_url, state = linkedin.authorization_url(authorization_base_url) # print 'Please go here and authorize,', authorization_url # session = requests.Session() # response = session.get(authorization_url) # print response.__dict__ # print '\n\nLook here! ', response.status_code # print '\n\nLook here! ', response.history # print '\n\nLook here! ', response.url # print '\n\nLook here! ', response.text # # Get the authorization verifier code from the callback url # redirect_response = raw_input('Paste the full redirect URL here:')
def refresh_access_token(self, username, token_name): if OAuth2Session is None: raise ImportError("No module named OAuth2Session") # load the refresh token refresh_token_path = os.path.join(self.cred_dir, username, token_name + '.top') try: with open(refresh_token_path, 'r') as f: refresh_token = json.load(f) except IOError as ie: self.log.error("Could not open refresh token %s: %s", refresh_token_path, str(ie)) return False except ValueError as ve: self.log.error( "The format of the refresh token file %s is invalid; could not parse as JSON: %s", refresh_token_path, str(ve)) return False # load metadata metadata_path = os.path.join(self.cred_dir, username, token_name + '.meta') try: with open(metadata_path, 'r') as f: token_metadata = json.load(f) except IOError as ie: self.log.error("Could not open metadata file %s: %s", metadata_path, str(ie)) return False except ValueError as ve: self.log.error( "The metadata file at %s is invalid; could not parse as JSON: %s", metadata_path, str(ve)) return False # refresh the token (provides both new refresh and access tokens) oauth_client = OAuth2Session(token_metadata['client_id'], token=refresh_token) new_token = oauth_client.refresh_token( token_metadata['token_url'], client_id=token_metadata['client_id'], client_secret=token_metadata['client_secret']) try: refresh_token = {u'refresh_token': new_token.pop('refresh_token')} except KeyError: self.log.error("No %s refresh token returned for %s", token_name, username) return False # write tokens to tmp files (tmp_fd, tmp_refresh_token_path) = tempfile.mkstemp(dir=self.cred_dir) with os.fdopen(tmp_fd, 'w') as f: json.dump(refresh_token, f) (tmp_fd, tmp_access_token_path) = tempfile.mkstemp(dir=self.cred_dir) with os.fdopen(tmp_fd, 'w') as f: json.dump(new_token, f) # atomically move new tokens in place access_token_path = os.path.join(self.cred_dir, username, token_name + '.use') try: atomic_rename(tmp_access_token_path, access_token_path) atomic_rename(tmp_refresh_token_path, refresh_token_path) except OSError as e: self.log.error(e) return False else: return True
group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-d", "--delete", action='store_true', help="delete all accounts in CSV from Red Hat Cloud Access") group.add_argument("-a", "--add", action='store_true', help="add all accounts in CSV to Red Hat Cloud Access") args = parser.parse_args() # Step 1: we obtain a session token from the openid SSO API, using the offlineToken created # in the customer portal https://access.redhat.com/management/api offlineToken = "eyJ.....r0" client_id = 'rhsm-api' oauthSession = OAuth2Session( client=Client(client_id=client_id, refresh_token=offlineToken)) openidUrl = 'https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token' sessionToken = oauthSession.refresh_token(token_url=openidUrl, client_id=client_id) # Step 2: We use the sessionToken to authenticate our request to add or delete CCSP accounts # to the registered providers in our Red Hat account using a CSV list like this: # ccsp;accountNr;nickName # AWS;123456789012;Project-X session = requests.Session() headers = { "Authorization": "Bearer %s" % (sessionToken['access_token']), "Content-Type": "application/json" } with open(args.csv, newline='') as ccspAccounts: reader = csv.DictReader(ccspAccounts, delimiter=';')
def create_raw_session(self): return OAuth2Session(CLIENT_ID, token=self.access_token, scope=self.access_token['scope'])
def main(): logging.basicConfig(level=logging.INFO) search_term = parse_args() verifier = make_verifier(Ed25519_PUBLIC_KEY) if isinstance(search_term, str) and search_term.lower().startswith('https://'): base_url = search_term info_url = base_url else: servers = list_servers(SERVER_URI, verifier=verifier) secure_internet = [ s for s in servers if s['server_type'] == 'secure_internet' ] institute_access = [ s for s in servers if s['server_type'] == 'institute_access' ] orgs = list_orgs(ORGANISATION_URI, verifier=verifier) choice = menu(institutes=institute_access, orgs=orgs, search_term=search_term) if not choice: exit(1) type_, base_url = choice if type_ == 'secure_internet_home': secure_internets = [ s for s in secure_internet if s['base_url'] == base_url ] info_url = secure_internet_choice(secure_internets) else: info_url = base_url exists = get_entry(base_url) if exists: token, api_base_uri, token_endpoint, authorization_endpoint = exists oauth = OAuth2Session(client_id=CLIENT_ID, token=token, auto_refresh_url=token_endpoint) else: api_base_uri, token_endpoint, auth_endpoint = get_info( info_url, verifier) oauth = get_oauth(token_endpoint, auth_endpoint) set_entry(base_url, oauth.token, api_base_uri, token_endpoint, auth_endpoint) oauth.refresh_token(token_url=token_endpoint) profiles = list_profiles(oauth, api_base_uri) profile_id = profile_choice(profiles) config = get_config(oauth, api_base_uri, profile_id) private_key, certificate = create_keypair(oauth, api_base_uri) if write_to_nm_choice(): save_connection(config, private_key, certificate) else: target = Path('eduVPN.ovpn').resolve() print(f"Writing configuration to {target}") write_config(config, private_key, certificate, target)
def oauth(): github = OAuth2Session(client_id) authorization_url, state = github.authorization_url(authorization_base_url) session['oauth_state'] = state return redirect(authorization_url)
client_id = os.getenv('SPOTIFY_CLIENT_ID') client_secret = os.getenv('SPOTIFY_CLIENT_SECRET') # a bogus redirect uri redirect_uri = "https://localhost" # the scope required for our API requests scope = r'user-read-playback-state user-modify-playback-state user-read-currently-playing' # Request URLs for Spotify request_authorization_url = "https://accounts.spotify.com/authorize" request_token_url = "https://accounts.spotify.com/api/token" # create our oauth client oauth = OAuth2Session(client_id=client_id, scope=scope, redirect_uri=redirect_uri) authorization_url, state = oauth. \ authorization_url(request_authorization_url) print('Go to %s and authorize access.' % authorization_url) authorization_response = input('Paste the full returned URL here: ') print("Auth response URL: '%s'" % authorization_response) token = oauth.fetch_token(request_token_url, client_secret=client_secret, authorization_response=authorization_response) bucket = os.getenv("SPOTIFY_BUCKET_NAME")
def callback(): github = OAuth2Session(client_id, state=session['oauth_state']) token = github.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url) session['oauth_token'] = token return redirect(url_for('profile'))
APP = flask.Flask(__name__, template_folder='static/templates') APP.debug = True APP.secret_key = 'development' APP.config['SESSION_TYPE'] = 'filesystem' if APP.secret_key == 'development': # ONLY TO BE USED IN DEVELOPMENT import os os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # allows http requests os.environ[ 'OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1' # allows tokens to contain additional permissions Session(APP) SOCKETIO = SocketIO(APP, manage_session=False, async_mode="gevent") MSGRAPH = OAuth2Session(config.CLIENT_ID, redirect_uri=config.REDIRECT_URI, scope=config.SCOPES) @APP.route('/') def homepage(): """Render the home page.""" if 'VIEW_DATA' not in flask.session: flask.session['VIEW_DATA'] = { } # used to store items that should be rendered in the HTML if 'access_token' in flask.session: if 'email' not in flask.session or 'username' not in flask.session: return flask.redirect(flask.url_for('get_my_email_address')) if 'SecurityEvents.ReadWrite.All' not in flask.session['scopes']: return flask.render_template( 'Admin_consent.html',
import yaml from oauthlib.oauth2 import BackendApplicationClient from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import requests with open("../config.yml", 'r') as stream: config = yaml.safe_load(stream) serviceURL = config.get('registry_service_url') # get a token scope = ['configPlatform'] auth = HTTPBasicAuth(config.get('key'), config.get('secret')) client = BackendApplicationClient(client_id=config.get('key'), scope=scope) wskey = OAuth2Session(client=client) try: token = wskey.fetch_token(token_url=config.get('token_url'), auth=auth) try: r = wskey.get(serviceURL + "/institution/data/128807", headers={"Accept": "application/json"}) r.raise_for_status result = r.json() if result.get('content').get('institution'): print( result.get('content').get('institution').get( 'nameLocation').get('institutionName')) else: print( result.get('content').get('section').get('nameLocation').get(
# This information is obtained upon registration of a new Outlook Application client_id = '---client-id---' client_secret = '---client-secret---' # OAuth endpoints given in Outlook API documentation authorization_base_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize' token_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token' scope = [ 'Group.Read.All', 'Calendars.Read', 'Contacts.Read', 'email', 'Files.Read', 'Mail.Read', 'Notes.Read', 'openid', 'People.Read', 'profile', 'Sites.Read.All', 'Tasks.Read', 'User.Read' ] redirect_uri = 'https://localhost/' # Should match Site URL from requests_oauthlib import OAuth2Session outlook = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri) # Redirect the user owner to the OAuth provider (i.e. Outlook) using an URL with a few key OAuth parameters. authorization_url, state = outlook.authorization_url(authorization_base_url) print('Please go here and authorize,', authorization_url) # Get the authorization verifier code from the callback url redirect_response = input('Paste the full redirect URL here:') # Fetch the access token token = outlook.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response) print(token) # Fetch a protected resource, i.e. calendar information
def get_oauth_token(self,request_url): oauth = OAuth2Session(self.client_id, redirect_uri=self.redirect_uri,scope=self.scope, state=self.state) return oauth.fetch_token(self.oauth_token_url, authorization_response=request_url, auth=HTTPBasicAuth(self.client_id, self.client_secret) )