import requests from urllib.parse import urlencode, urlparse # Configuration details redirect_uri = '' client_id = '' client_secret = '' tenant_id = '' token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token" def get_authorization_code(): """Get authorization code by guiding the user to the authorization URL.""" auth_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize" params = { "client_id": client_id, "response_type": "code", "redirect_uri": redirect_uri, "scope": "openid profile email offline_access", "state": "12345" } # Generate the authorization URL authorization_request_url = auth_url + "?" + urlencode(params) print(f"Please open the following URL in your browser to grant permissions:") print(authorization_request_url) print("After granting permissions, you will be redirected to the provided redirect URI.") print("Copy and paste the full redirected URL here.") redirected_url = input("Enter the redirected URL: ") # Parse the authorization code from the redirected URL parsed_url = urlparse(redirected_url) query_params = dict(param.split('=') for param in parsed_url.query.split('&') if '=' in param) authorization_code = query_params.get("code") if not authorization_code: print("Authorization code not found in the redirected URL. Please ensure the URL is correct.") return None return authorization_code def get_access_token(authorization_code, redirect_uri): """Exchange the authorization code for an access token and a refresh token.""" data = { "grant_type": "authorization_code", "client_id": client_id, "client_secret": client_secret, "redirect_uri": redirect_uri, "code": authorization_code } response = requests.post(token_url, data=data) if response.status_code == 200: token_data = response.json() access_token = token_data.get('access_token') refresh_token = token_data.get('refresh_token') return access_token, refresh_token else: print("Error fetching tokens:", response.text) return None, None if __name__ == "__main__": # Step 1: Get the authorization code authorization_code = get_authorization_code() if not authorization_code: print("Failed to retrieve the authorization code. Exiting.") else: # Step 2: Use the authorization code to fetch tokens # Create a sharepoint_credentials.txt in Desktop and copy the file path and paste it inside the closed brackets.Your tokens will write inside the .txt file access_token, refresh_token = get_access_token(authorization_code, redirect_uri) if access_token and refresh_token: # Step 3: Save the tokens and authorization code to a file with open("C:\\Users\\gurulakshmi\\Desktop\\sharepoint_credentials.txt", "w") as file: file.write(f"Auth code: \n{authorization_code}\n\n") file.write(f"Access token: \n{access_token}\n\n") file.write(f"Refresh token: \n{refresh_token}\n\n") print("Tokens successfully saved to 'sharepoint_credentials.txt'.") else: print("Failed to obtain tokens.")