def get_url(client_id): """Create oauth client and generate authorisatio code URL.""" oauthlib_client = oauth2.WebApplicationClient(client_id) # This is the URL construction for getting the authorisation code authorize_url = oauthlib_client.prepare_request_uri( GOOGLE_OAUTH2_AUTH_ENDPOINT, redirect_uri=CALLBACK_URL, scope=SCOPE) return authorize_url
def main(): oauthlib_client = oauth2.WebApplicationClient(CLIENT_ID) authorize_url = oauthlib_client.prepare_request_uri( GOOGLE_OAUTH2_AUTH_ENDPOINT, redirect_uri=CALLBACK_URL, scope=SCOPE) print ('Log in to your DFA account and open the following URL: \n%s\n' % authorize_url) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() post_body = oauthlib_client.prepare_request_body( client_secret=CLIENT_SECRET, code=code, redirect_uri=CALLBACK_URL) if sys.version_info[0] == 3: post_body = bytes(post_body, 'utf8') request = urllib2.Request(GOOGLE_OAUTH2_GEN_ENDPOINT, post_body, OAUTH2_REFRESH_HEADERS) if HTTPS_PROXY: request.set_proxy(HTTPS_PROXY, 'https') raw_response = urllib2.urlopen(request).read().decode() oauth2_credentials = oauthlib_client.parse_request_body_response(raw_response) print ('Your access token is %s and your refresh token is %s' % (oauth2_credentials['access_token'], oauth2_credentials['refresh_token'])) print ('You can cache these credentials into a yaml file with the ' 'following keys:\ndfa:\n client_id: %s\n client_secret: %s\n' ' refresh_token: %s\n' % (CLIENT_ID, CLIENT_SECRET, oauth2_credentials['refresh_token']))
def oauth(): """ 当用户点击该链接时,把用户重定向到Gitlab的OAuth2登录页面。 """ client = oauth2.WebApplicationClient(OAUTH["client_id"]) state = client.state_generator() # 生成的随机的state参数 auth_url = client.prepare_request_uri(OAUTH["auth_url"], OAUTH["redirect_uri"], OAUTH["scope"], state) # 构造完整的auth_url,接下来要让用户重定向到它 session["oauth_state"] = state return redirect(auth_url)
def web_oauth(self, request): '''Return the absolute uri for web authentication. Uses the :attr:`WEB_AUTH_URL` attribute as the base url. ''' redirect_uri = self.build_uri(request.absolute_uri(), self.name, 'callback') sessions = request.app.extensions['sessions'] client = oauth2.WebApplicationClient(self.client_id) state = sessions.get_or_create_csrf_token(request) return client.prepare_request_uri(self.WEB_AUTH_URL, scope=self.client_scope, redirect_uri=redirect_uri, state=state)
def get_token(client_id, client_secret, ads_code): """Get refresh token using authentication and client credentials.""" oauthlib_client = oauth2.WebApplicationClient(client_id) # Prepare the access token request body --> makes a # request to the token endpoint by adding the following parameters post_body = oauthlib_client.prepare_request_body( client_secret=client_secret, code=ads_code, redirect_uri=CALLBACK_URL) # URL request r = request.Request(GOOGLE_OAUTH2_GEN_ENDPOINT, post_body.encode('utf-8'), OAUTH2_REFRESH_HEADERS) if HTTPS_PROXY: r.set_proxy(HTTPS_PROXY, 'https') raw_response = request.urlopen(r).read().decode() oauth2_credentials = oauthlib_client.parse_request_body_response( raw_response) # Return the refresh token return oauth2_credentials['refresh_token']
def get_token(client_id, client_secret, ads_code): oauthlib_client = oauth2.WebApplicationClient(client_id) # Prepare the access token request body --> makes a # request to the token endpoint by adding the following parameters post_body = oauthlib_client.prepare_request_body( client_secret=client_secret, code=ads_code, redirect_uri=CALLBACK_URL) # URL request request = urllib2.Request(GOOGLE_OAUTH2_GEN_ENDPOINT, post_body, OAUTH2_REFRESH_HEADERS) if HTTPS_PROXY: request.set_proxy(HTTPS_PROXY, 'https') # Open the given url, read and decode into raw_response raw_response = urllib2.urlopen(request).read().decode() # Parse the JSON response body given in raw_response oauth2_credentials = oauthlib_client.parse_request_body_response( raw_response) # Return the refresh token token = oauth2_credentials['refresh_token'] return token
def oauth_callback(): """ 用户在同意授权之后,会被Gitlab重定向回到这个URL。 """ # 解析得到code client = oauth2.WebApplicationClient(OAUTH["client_id"]) code = client.parse_request_uri_response( request.url, session["oauth_state"]).get("code") # 请求token body = client.prepare_request_body(code, redirect_uri=OAUTH["redirect_uri"], client_secret=OAUTH["client_secret"]) r = requests.post(OAUTH["token_url"], body) access_token = r.json().get("access_token") # 查询用户名并储存 api_path = "/user" url = OAUTH["api_url"] + "/" + api_path + "?" + \ urlencode({"access_token": access_token}) r = requests.get(url) data = r.json() session["username"] = data.get("username") session["access_token"] = access_token # 以后存到用户表中 return redirect("/")
def gclient_action(self, context): """Handles Google+ sign-in postmessage callback Exchange the one-time authorization code for a token and store the token in the session.""" if context.environ['REQUEST_METHOD'].upper() != 'POST': raise wsgi.MethodNotAllowed if not self.google_id: raise wsgi.BadRequest # the wsgi.session_decorator took care of checking the CSRF # token already code = context.get_form_string('code') if code == 'logout': # this is the logout action context.session.del_owner() context.set_status(200) return self.json_response( context, json.dumps("session owner logged out")) # swap this code for an OAuth 2 access token gclient = oauth2.WebApplicationClient(client_id=self.google_id) body = gclient.prepare_request_body( code=code, client_secret=self.google_secret, redirect_uri='postmessage') req = http.ClientRequest("https://accounts.google.com/o/oauth2/token", method="POST", entity_body=str(body)) req.set_accept("application/json") req.set_content_type('application/x-www-form-urlencoded;charset=UTF-8') self.http.process_request(req) if req.status != 200: logging.warn("OAuth request returned status: %i", req.status) raise wsgi.BadRequest gclient.parse_request_body_response(req.res_body) url, headers, data = gclient.add_token( 'https://www.googleapis.com/oauth2/v1/userinfo', http_method="GET") req = http.ClientRequest(url) req.set_accept("application/json") req.set_content_type('application/x-www-form-urlencoded;charset=UTF-8') for h, v in headers.items(): req.set_header(h, v) self.http.process_request(req) if req.status != 200: logging.warn("OAuth request returned status: %i", req.status) raise wsgi.BadRequest userinfo = json.loads(req.res_body.decode('utf-8')) current_owner = context.session.get_owner() if current_owner: if (current_owner['IDType'].value == 'google' and current_owner['ID'].value == userinfo['id']): # we're already logged in to this session logging.warn("google user already logged in") context.set_status(200) return self.json_response( context, json.dumps("Already logged in")) # clear this link with context.session.entity['Owner'].OpenCollection() as \ collection: collection.clear() logging.debug("Google user logged in: %s <%s>", userinfo['name'], userinfo['email']) with self.container['Owners'].OpenCollection() as collection: # let's find this user in our database id = edm.EDMValue.NewSimpleValue(edm.SimpleType.String) id.set_from_value(userinfo['id']) filter = odata.CommonExpression.from_str( "IDType eq 'google' and ID eq :id", {'id': id}) collection.set_filter(filter) owners = collection.values() if len(owners) == 0: # first time we ever saw this person, create an entry owner = collection.new_entity() owner['Key'].set_from_value( wsgi.key60('gmail:' + userinfo['id'])) owner['IDType'].set_from_value('google') owner['ID'].set_from_value(userinfo['id']) owner['GivenName'].set_from_value(userinfo['given_name']) owner['FamilyName'].set_from_value(userinfo['family_name']) owner['FullName'].set_from_value(userinfo['name']) owner['Email'].set_from_value(userinfo['email']) owner['Session'].BindEntity(context.session.entity) # and create them a silo for their data with owner['Silo'].Target().OpenCollection() as silos: silo = silos.new_entity() silo['ID'].set_from_value(owner['Key'].value) silo['Slug'].set_from_value(userinfo['email']) silos.insert_entity(silo) owner['Silo'].BindEntity(silo) collection.insert_entity(owner) # and finally create a default consumer for them with silo['Consumers'].OpenCollection() as collection: consumer = lti.ToolConsumer.new_from_values( collection.new_entity(), self.app_cipher, "default") collection.insert_entity(consumer.entity) elif len(owners) == 1: # we already saw this user owner = owners[0] # update the record from the latest userinfo owner['GivenName'].set_from_value(userinfo['given_name']) owner['FamilyName'].set_from_value(userinfo['family_name']) owner['FullName'].set_from_value(userinfo['name']) owner['Email'].set_from_value(userinfo['email']) owner['Session'].BindEntity(context.session.entity) collection.update_entity(owner) else: logging.error("Duplicate google owner: %s <%s>", id.value, userinfo['email']) raise RuntimeError("Unexpected duplicate in Owners") context.set_status(200) return self.json_response( context, json.dumps("%s now logged in" % userinfo['name']))
file = open("googleAPI.txt") line = file.readline().split(",") GOOGLE_CLIENT_ID = line[0] os.environ.get("GOOGLE_CLIENT_ID", None) GOOGLE_CLIENT_SECRET = line[1] os.environ.get("GOOGLE_CLIENT_SECRET", None) GOOGLE_DISCOVERY_URL = ( "https://accounts.google.com/.well-known/openid-configuration") # using flask"s login manager for user session mgmt setup host = "172.31.30.44" port = 5300 # OAuth 2 client setup client = oo.WebApplicationClient(GOOGLE_CLIENT_ID) dbName = "customer" dbURL = os.environ.get("dbURL") dbURL += dbName app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = dbURL app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False login_manager = LoginManager() login_manager.init_app(app) CORS(app) ######## GRAPHQL settings ##########
def __init__(self, client_id=None, client=None, **kw): if oauth2 is None: raise ImproperlyConfigured('%s requires oauthlib' % self.__class__.__name__) self._client = client or oauth2.WebApplicationClient(client_id, **kw)
def get_oauth_client(): client_id = app['oauth_client_id'] return oauth2.WebApplicationClient(client_id)
def __init__(self, client_id=None, client=None, **kwargs): self._client = client or oauth2.WebApplicationClient( client_id, **kwargs)
from oauthlib import oauth2 from dotenv import load_dotenv load_dotenv() CLIENT_ID = os.getenv("CLIENT_ID") CLIENT_SECRET = os.getenv("CLIENT_SECRET") redirect_uri = os.getenv("REDIRECT_URI") DATA = { 'response_type': "code", 'redirect_uri': redirect_uri, 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'client_id': CLIENT_ID, 'prompt': 'consent' } URL_DICT = { # Google OAuth URI 'google_oauth': 'https://accounts.google.com/o/oauth2/v2/auth', # URI to generate token to access Google API 'token_gen': 'https://oauth2.googleapis.com/token', # URI to get the user info 'get_user_info': 'https://www.googleapis.com/oauth2/v3/userinfo' } CLIENT = oauth2.WebApplicationClient(CLIENT_ID) REQ_URI = CLIENT.prepare_request_uri(uri=URL_DICT['google_oauth'], redirect_uri=DATA['redirect_uri'], scope=DATA['scope'], prompt=DATA['prompt'])