def load_cache(request): # Check for a token cache in the session cache = msal.SerializableTokenCache() if request.session.get('token_cache'): cache.deserialize(request.session['token_cache']) return cache
def _load_cache(): # TODO: Load the cache from `msal`, if it exists cache = msal.SerializableTokenCache() if session.get('token_cache'): cache.deserialize(session['token_cache']) app.logger.info('_load_cache: Session loaded from the cache.') return cache
def cache(self): """Get a token cache Load a token cache from disk, or create a new cache instance. Cache instances map onto the backing storage, and will attempt to synchronize. To ensure consistency, token caches always be obtained with this method, and never constructed explicitly. Returns ------- cache : msal.SerializeableTokenCache Notes ----- This function is meant for internal use. """ path = self.path() if path in self.cachecache: return self.cachecache[path] pathlib.Path(self.root).mkdir(exist_ok = True) cache = msal.SerializableTokenCache() with contextlib.suppress(FileNotFoundError): with open(path) as f: cache.deserialize(f.read()) self.cachecache[path] = cache return cache
async def authorized(request: Request) -> RedirectResponse: # see https://github.com/Azure-Samples/ms-identity-python-webapp/blob/e342e93a2a7e0cc4d4955c20660e6a81fd2536c5/app.py#L35-L45 # for try except pattern. Kind of annoying, means you may have to click sign in twice try: cache = msal.SerializableTokenCache() flow = request.session.get("flow", {}) result = build_msal_app( cache=cache).acquire_token_by_auth_code_flow( flow, dict(request.query_params), scopes=get_auth_settings().scopes, ) # Remove flow cookie request.session.pop("flow", None) # Just store the oid (https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens) in a signed cookie oid = result.get("id_token_claims").get("oid") await f_save_cache(oid, cache) request.session["user"] = oid except ValueError as error: logging.debug("%s", error) return RedirectResponse(url=request.url_for("home"), status_code=302)
def __init__(self, args): self.cache_file = os.path.join(args.statedir, "tokencache.bin") self.cache = msal.SerializableTokenCache() # pylint: disable=invalid-name if os.path.exists(self.cache_file): self.cache.deserialize(open(self.cache_file, "r").read()) logging.debug(f'Loaded cache {self.cache_file}') atexit.register(self.__atexit)
def _load_cache(): # TODO: Load the cache from `msal`, if it exists cache = msal.SerializableTokenCache() if session.get('token_cache'): cache.deserialize(session['token_cache']) return cache
def setUp(self): self.environment_in_cache = "sts.windows.net" self.authority_url_in_app = "https://login.microsoftonline.com/common" self.scopes = ["s1", "s2"] uid = "uid" utid = "utid" self.account = {"home_account_id": "{}.{}".format(uid, utid)} self.client_id = "my_app" self.access_token = "access token for testing authority aliases" self.cache = msal.SerializableTokenCache() self.cache.add( { "client_id": self.client_id, "scope": self.scopes, "token_endpoint": "https://{}/common/oauth2/v2.0/token".format( self.environment_in_cache), "response": TokenCacheTestCase.build_response( uid=uid, utid=utid, access_token=self.access_token, refresh_token="some refresh token"), } ) # The add(...) helper populates correct home_account_id for future searching self.app = ClientApplication(self.client_id, authority=self.authority_url_in_app, token_cache=self.cache)
def get_token_cache(cache_name: str) -> msal.SerializableTokenCache: """Attempt to load a TokenCache from a file. If the file does not exist then return an empty TokenCache.""" cache = msal.SerializableTokenCache() if os.path.exists(cache_name): cache.deserialize(open(cache_name, "r").read()) return cache
def get_auth(): with open('parameters.json', 'r') as file: config = json.load(file) cache_file = os.path.join('private', 'my_cache.bin') cache = msal.SerializableTokenCache() if os.path.exists(cache_file): cache.deserialize(open(cache_file, "r").read()) atexit.register(lambda: open(cache_file, "w").write(cache.serialize()) if cache.has_state_changed else None) app = msal.PublicClientApplication(config["client_id"], authority=config["authority"], token_cache=cache) result = None accounts = app.get_accounts() if accounts: # for a in accounts: # print(a["username"]) chosen = accounts[0] result = app.acquire_token_silent(config["scope"], account=chosen) if not result: logging.error( "No suitable token exists in cache. Let's get a new one from AAD.") flow = app.initiate_device_flow(scopes=config["scope"]) if "user_code" not in flow: raise ValueError("Fail to create device flow. Err: %s" % json.dumps(flow, indent=4)) print(flow["message"]) result = app.acquire_token_by_device_flow(flow) return result['access_token']
def __init__(self, config): self.cache = msal.SerializableTokenCache() self.app_instance = None self.session = None self.AUTHENTICATION_TENANT_AUTHORITY = config.AUTHENTICATION_TENANT_AUTHORITY self.AUTHENTICATION_CLIENT_ID = config.AUTHENTICATION_CLIENT_ID self.AUTHENTICATION_SCOPE = [config.AUTHENTICATION_SCOPE]
def initialize_cache(self): logger.debug(f"Using path '{self.cache_path}' for AAD token cache") self.token_cache = msal.SerializableTokenCache() if os.path.exists(self.cache_path): with open(self.cache_path, "r") as cache: self.token_cache.deserialize(cache.read())
def Authorize(): global token global fullname print("Starting authentication workflow.") try: cache = msal.SerializableTokenCache() if os.path.exists('token_cache.bin'): cache.deserialize(open('token_cache.bin', 'r').read()) atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None) app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY, token_cache=cache) accounts = app.get_accounts() result = None if len(accounts) > 0: result = app.acquire_token_silent(SCOPES, account=accounts[0]) if result is None: # Create QR code qr = pyqrcode.create("https://microsoft.com/devicelogin") print(qr.terminal(module_color=0, background=231, quiet_zone=1)) # Initiate flow flow = app.initiate_device_flow(scopes=SCOPES) if 'user_code' not in flow: raise Exception('Failed to create device flow') print(flow['message']) result = app.acquire_token_by_device_flow(flow) token = result['access_token'] print("Aquired token") token_claim = result['id_token_claims'] print("Welcome " + token_claim.get('name') + "!") fullname = token_claim.get('name') return True if 'access_token' in result: token = result['access_token'] try: result = requests.get(f'{ENDPOINT}/me', headers={'Authorization': 'Bearer ' + result['access_token']}, timeout=5) result.raise_for_status() y = result.json() fullname = y['givenName'] + " " + y['surname'] print("Token found, welcome " + y['givenName'] + "!") return True except requests.exceptions.HTTPError as err: if err.response.status_code == 404: printerror("MS Graph URL is invalid!") exit(5) elif err.response.status_code == 401: printerror("MS Graph is not authorized. Please reauthorize the app (401).") return False except requests.exceptions.Timeout as timeerr: printerror("The authentication request timed out. " + str(timeerr)) else: raise Exception('no access token in result') except Exception as e: printerror("Failed to authenticate. " + str(e)) sleep(2) return False
def _load_cache(): # TODO[Done]: Load the cache from `msal`, if it exists cache = msal.SerializableTokenCache() if session.get("token_cache"): cache.deserialize(session["token_cache"]) return cache
def _load_cache(): # Serialization token cache object for MSAL cache = msal.SerializableTokenCache() # Checks if token cache is stored in session and deserializes token cache and returns the cache if session.get("token_cache"): cache.deserialize(session["token_cache"]) return cache
def __init__(self, user_name: str, client_id: str, scopes: List[str]): self.cache = msal.SerializableTokenCache() if CACHE_PATH.exists(): self.cache.deserialize(open(CACHE_PATH, "r").read()) atexit.register(self._serialize_cache) self.user_name = user_name self.app = msal.PublicClientApplication(client_id=client_id, token_cache=self.cache) self.scopes = scopes
def _load_cache(outlook_cache): ''' Function to load a Serialized token Cache object\n @@Param outlook_cache: Modal of OutlookServerDetails @@Returns: a cache object ''' cache = msal.SerializableTokenCache() if outlook_cache and outlook_cache.token_cache: cache.deserialize(outlook_cache.token_cache) return cache
def authenticate(logger=None): CLIENT_ID = os.environ['CLIENT_ID'] AUTHORITY = f'https://login.microsoftonline.com/consumers/' SCOPES = [ 'Files.ReadWrite.All', 'User.Read', ] # Token caching # Each time you run the minimal example above, you will have to # click on the link and log in with your web browser. We can avoid # having to do this every time by adding a serializable token cache # to the MSAL app when it is created: cache = msal.SerializableTokenCache() if os.path.exists('token_cache.bin'): cache.deserialize(open('token_cache.bin', 'r').read()) atexit.register( lambda: open('token_cache.bin', 'w').write(cache.serialize())\ if cache.has_state_changed else None) app = msal.PublicClientApplication( CLIENT_ID, authority=AUTHORITY, token_cache=cache) # get access token accounts = app.get_accounts() result = None if len(accounts) > 0: result = app.acquire_token_silent(SCOPES, account=accounts[0]) if result is None: # leverage "device flow" authentication that allows us to authenticate # the app on behalf of a user rather then using an API key or having # to store and supply a username / password with each request flow = app.initiate_device_flow(scopes=SCOPES) if 'user_code' not in flow: raise Exception('Failed to create device flow') if logger: logger.info(flow['message']) result = app.acquire_token_by_device_flow(flow) if 'access_token' in result: access_token = result['access_token'] result = requests.get( f'{ENDPOINT}/me', headers={'Authorization': 'Bearer ' + access_token}) result.raise_for_status() if logger: logger.info(result.json()) else: raise Exception('no access token in result') return access_token
def _load_cache(): """ Used to load cached Microsoft mail account user's credentials :return: The stored cache """ # TODO: Load the cache from `msal`, if it exists cache = msal.SerializableTokenCache() if session.get('token_cache'): cache.deserialize(session['token_cache']) return cache
def _load_cache(self, request): """azure ad の認証エンドポイント用データ作成 Args: cache(object): azure adのAPI scope 基本readのみ Returns: object: クライアントに返却するResonse情報 """ cache = msal.SerializableTokenCache() if request.session.get('token_cache'): cache.deserialize(request.session['token_cache']) return cache
def load_token_cache(): """ Load token from cache file """ cache = msal.SerializableTokenCache() if os.path.exists(TOKEN_CACHE): with open(TOKEN_CACHE, "r") as tc: cache.deserialize(tc.read()) return cache
def token_cache(): if not os.path.isdir(cache_dir): os.makedirs(cache_dir) cache = msal.SerializableTokenCache() if os.path.exists(cache_path): cache.deserialize(open(cache_path, "r").read()) atexit.register(lambda: open(cache_path, "w").write(cache.serialize()) if cache.has_state_changed else None) return cache
def load_cache(request: Request): """ Process a cache that exists in the users cookies :param request: request object sent to the calling functions body :return: Returns the processed cache from the users session """ cache = msal.SerializableTokenCache() cookie_cache = request.cookies.get("token_cache") if cookie_cache: cache.deserialize(cookie_cache) return cache
def init_cache(self) -> None: # Ensure the token_path directory exists try: dir_name = os.path.dirname(self.token_path) with _temporary_umask(_ACCESSTOKENCACHE_UMASK): os.makedirs(dir_name) except FileExistsError: pass self.token_cache = msal.SerializableTokenCache() if os.path.exists(self.token_path): with open(self.token_path, "r") as handle: self.token_cache.deserialize(handle.read())
def generate_access_token(app_id, scopes): # Save Session Token as a token file access_token_cache = msal.SerializableTokenCache() # read the token file if os.path.exists('ms_graph_api_token.json'): access_token_cache.deserialize( open("ms_graph_api_token.json", "r").read()) token_detail = json.load(open('ms_graph_api_token.json', )) print(token_detail) token_detail_key = list(token_detail['AccessToken'].keys())[0] token_expiration = datetime.fromtimestamp( int(token_detail['AccessToken'][token_detail_key]['expires_on'])) if datetime.now() > token_expiration: os.remove('ms_graph_api_token.json') access_token_cache = msal.SerializableTokenCache() # assign a SerializableTokenCache object to the client instance client = msal.PublicClientApplication(client_id=app_id, token_cache=access_token_cache) accounts = client.get_accounts() if accounts: # load the session token_response = client.acquire_token_silent(scopes, accounts[0]) else: # authetnicate your accoutn as usual flow = client.initiate_device_flow(scopes=scopes) print('user_code: ' + flow['user_code']) webbrowser.open('https://microsoft.com/devicelogin') token_response = client.acquire_token_by_device_flow(flow) with open('ms_graph_api_token.json', 'w') as _f: _f.write(access_token_cache.serialize()) return token_response
def __init__(self, oauth_settings: OAuthSettings, serialized_token_file=None): self.oauth_settings = oauth_settings self.serialized_token_file = serialized_token_file self.token_cache = msal.SerializableTokenCache() serialized_token = self.load_token() if serialized_token: self.token_cache.deserialize(serialized_token) super().__init__(client_id=oauth_settings.app_id, client_credential=oauth_settings.app_secret, authority=oauth_settings.authority, token_cache=self.token_cache)
def save_one_drive_token(request): """This view is redirected to after the OneDrive authorization process.""" root_path = request.session.get("root_path") cache = msal.SerializableTokenCache() msal_app = build_msal_app(cache=cache) result = msal_app.acquire_token_by_auth_code_flow( request.session["auth_flow"], request.GET) username = result["id_token_claims"]["preferred_username"] if request.session["object_type"] == "datalake": return create_one_drive_datalake(username, root_path, cache, request) else: return create_one_drive_datastore(username, root_path, cache, request)
def _build_new_app_state(self, crypt): cache = msal.SerializableTokenCache() state = str(uuid.uuid4()) auth_url = self._get_auth_url(cache, state) wsgi_app = WSGIRedirectionApp(MSOauth2.SUCCESS_MESSAGE) http_server = simple_server.make_server( self._redirect_host, int(self._redirect_port), wsgi_app, handler_class=WSGIRequestHandler, ) if not self._browser_activated: print("Please navigate to this url: " + auth_url) else: webbrowser.open(auth_url, new=2, autoraise=True) http_server.handle_request() auth_response = wsgi_app.last_request_uri http_server.server_close() parsed_auth_response = parse_qs(auth_response) code_key = self._redirect_uri + "?code" if code_key not in parsed_auth_response: raise Exception( f"A coder key was expected from {parsed_auth_response}") auth_code = parsed_auth_response[code_key] result = self._build_msal_app( cache).acquire_token_by_authorization_code( auth_code, scopes=self._scopes, redirect_uri=self._redirect_uri) if result.get("access_token") is None: raise Exception( f"Something went wrong during authorization Server returned: {result}" ) token = result["access_token"] app = {} app["cache"] = cache app["crypt"] = crypt return app, token
def setUp(self): self.authority_url = "https://login.microsoftonline.com/common" self.authority = msal.authority.Authority(self.authority_url) self.scopes = ["s1", "s2"] self.uid = "my_uid" self.utid = "my_utid" self.account = {"home_account_id": "{}.{}".format(self.uid, self.utid)} self.frt = "what the frt" self.cache = msal.SerializableTokenCache() self.cache.add({ # Pre-populate a FRT "client_id": "preexisting_family_app", "scope": self.scopes, "token_endpoint": "{}/oauth2/v2.0/token".format(self.authority_url), "response": TokenCacheTestCase.build_response( uid=self.uid, utid=self.utid, refresh_token=self.frt, foci="1"), }) # The add(...) helper populates correct home_account_id for future searching
def get_access_token(): mscache = msal.SerializableTokenCache() if os.path.exists("outlooktoken.bin"): mscache.deserialize(open("outlooktoken.bin", "r").read()) atexit.register(lambda: open("outlooktoken.bin", "w").write( mscache.serialize()) if mscache.has_state_changed else None) app = msal.PublicClientApplication( "3b49f0d7-201a-4b5d-b2b4-8f4c3e6c8a30", authority="https://login.microsoftonline.com/consumers", token_cache=mscache) result = None accounts = app.get_accounts() if accounts: chosen = accounts[0] result = app.acquire_token_silent( ["https://graph.microsoft.com/Calendars.Read"], account=chosen) if not result: logging.info("No token exists in cache, login is required.") flow = app.initiate_device_flow( scopes=["https://graph.microsoft.com/Calendars.Read"]) if "user_code" not in flow: raise ValueError("Fail to create device flow. Err: %s" % json.dumps(flow, indent=4)) print("") print(flow["message"]) sys.stdout.flush() result = app.acquire_token_by_device_flow(flow) logging.debug(result) if "access_token" in result: return result["access_token"] else: logging.error(result.get("error")) logging.error(result.get("error_description")) logging.error(result.get("correlation_id")) raise Exception(result.get("error"))
def token(self): """ Loads a token from cache Loads a token that has previously been cached by login() or the oneseismic-login command. This function is designed to be executed non-interactively and will fail if the token can not be loaded from cache and refreshed without user interaction. """ if not self.app: config_path = os.path.join(self.cache_dir or XDG_CACHE_HOME, "oneseismic", "config.json") try: config = json.load(open(config_path)) except FileNotFoundError: raise RuntimeError("No credentials found in cache. Log in " "using oneseismic-login or login()") cache_file = os.path.join(self.cache_dir or XDG_CACHE_HOME, "oneseismic", "accessToken.json") cache = msal.SerializableTokenCache() cache.deserialize(open(cache_file, "r").read()) atexit.register( lambda: open(cache_file, "w").write(cache.serialize())) self.app = msal.PublicClientApplication( config['client_id'], authority=config['auth_server'], token_cache=cache, ) self.scopes = config['scopes'] account = self.app.get_accounts()[0] result = self.app.acquire_token_silent(self.scopes, account=account) if "access_token" not in result: raise RuntimeError( "A token was found in cache, but it does not appear to " "be valid. Try logging in again using oneseismic-login " "or login()") return {"Authorization": "Bearer " + result["access_token"]}