Search code examples
pythonflaskgoogle-oauthgmail-apigoogle-api-python-client

How to get the right JSON credentials file from google cloud console project?


I am trying to authenticate my flask web app to send password reset emails using the google Gmail API, I have already set up my project and acquired my credentials json file in the google console. When I run my code, the following method in the class handling the whole authentication process catches the DefaultCredentialsError


def get_credentials(self, authorization_code=None):
    if self.credentials is not None:
        return self.credentials

    # Load the saved credentials
    try:
        creds = google.auth.load_credentials_from_file(Config.Config.PATH)
    except DefaultCredentialsError:
        flash('SETUP INCOMPLETE', 'warning')
        return redirect(url_for('home'))

the problem is with the file having a type None instead of one of the expected file types,,, this is the error message from the browser

google.auth.exceptions.DefaultCredentialsError: The file C:\Users\MARK KARIUKI\OneDrive\Documents/googleDocs/creds.json does not have a valid type. Type is None, expected one of ('authorized_user', 'service_account', 'external_account', 'external_account_authorized_user', 'impersonated_service_account', 'gdch_service_account').

how can I get a json file that has the required type? ,,, for my application I need the 'authorised user' type.

I have tried recreating the credentials a couple of time but the same details are included in the json file and no type key is included in the dictionary contained in the json file.


Solution

  • If you are creating a flask web app then you would probably want to create web application credentials. This will use Oauth2 to request consent of the user to access their gmail account and send emails on their behalf.

    You appear to have maybe created service account credentials. A service account is like a dummy user if you configure domain wide delegation on your google workspace account you can then impersonate any user on the domain and send emails on their behalf. however the code to authorize a service account is different then the code used for Oauth2 authorization

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_FILE_PATH,
        scopes=SCOPES)
    
    credentials = credentials.create_delegated(user_email)
    

    Remember service accounts only work with the gmail api if you use them with a google workspace domain account.