SCRT-HQ / PSGSuite

Powershell module for Google / G Suite API calls wrapped in handy functions. Authentication is established using a service account via P12 key to negate the consent popup and allow for greater handsoff automation capabilities
https://psgsuite.io/
Apache License 2.0
234 stars 66 forks source link

Initial setup issue: Login Required [401] #271

Closed RamblingCookieMonster closed 4 years ago

RamblingCookieMonster commented 4 years ago

Describe the bug

Followed docs for free/standard account, created oauth2 project, creds, downloaded creds, ran Get-GSGmailProfile -Verbose for initial auth, authed without issue, received:

> Get-GSGmailProfile -Verbose
VERBOSE: Building UserCredentials from ClientSecrets as user 'REDACTED@REDACTED' and prompting for authorization if necessary.
VERBOSE: Getting Gmail profile for user 'REDACTED@REDACTED'
Get-GSGmailProfile : Exception calling "Execute" with "0" argument(s): "Google.Apis.Requests.RequestError
Login Required [401]
Errors [
    Message[Login Required] Location[Authorization - header] Reason[required] Domain[global]
]
"
At line:1 char:1
+ Get-GSGmailProfile -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-GSGmailProfile

To Reproduce Steps to reproduce the behavior:

  1. Follow documentation to get up and running

Expected behavior Authentication works

Environment (please complete the following information):

Additional context

I'll go back and review, but everything looks and behaves right (in google GUI right up to granting permission) - maybe google changed something behind the scenes, or I did something wrong?

scrthq commented 4 years ago

Hey @RamblingCookieMonster ! Thanks for checking out PSGSuite 🙂 assuming you downloaded the client_secrets.json file? On your firstcommand run, did it open your browser to complete authentication at all?

RamblingCookieMonster commented 4 years ago

Hiyo! Yep, ran the initial Set-PSGSuite with ClientSecretsPath and AdminEmail set. Then when running other commands, everything worked as expected (Windows PowerShell launched a browsed, asked for permissions, and gave me a thumbs up, PowerShell core gave me a code to paste) - but after authenticating in the browser or pasting the code, I get the error indicated.

> Show-PSGsuiteConfig
ConfigName             : MyConfig
P12KeyPath             :
P12Key                 :
P12KeyPassword         :
P12KeyObject           :
ClientSecretsPath      : REDACTED.json
ClientSecrets          : {"installed":{"client_id":"REDACTED","project_
                         id":"REDACTED","auth_uri":"https://accounts
                         .google.com/o/oauth2/auth","token_uri":"https://oauth2.
                         googleapis.com/token","auth_provider_x509_cert_url":"ht
                         tps://www.googleapis.com/oauth2/v1/certs"}}
AppEmail               :
AdminEmail             : REDACTED@REDACTED
CustomerID             :
Domain                 :
Preference             :
ServiceAccountClientID :
Chat                   : {Spaces, Webhooks}
ConfigPath             : C:\Users\wframe\AppData\Local\powershell\SCRT
                         HQ\psgsuite\Configuration.psd1

Don't spend too much time, just poking around to see what I can do!

scrthq commented 4 years ago

@RamblingCookieMonster - No worries! Let me see if I can replicate :-)

scrthq commented 4 years ago

Also worth noting that occasionally I've seen some odd credential propagation time for new projects and service accounts. Going to run through a Gmail account set up to see where it leads me.

Are you using a non-admin account on a G Suite account or normal, free Gmail account for this?

scrthq commented 4 years ago

Hmmmm this is new:

image

scrthq commented 4 years ago

Alright, that was apparently just a red herring, still working ok for me, I'm not able to replicate 😕

image

Did you explicitly import the module first or did you autoimport by calling one of the functions directly? If you did not explicitly import, could you try the following from a fresh PowerShell session?

Import-Module PSGSuite
Get-GSGmailProfile -Verbose
RamblingCookieMonster commented 4 years ago

Hmm, I tried with a g.harvard.edu account, wonder if they block this, or if process is different. Will try with my normal e-mail and update - thanks!

scrthq commented 4 years ago

Got it! Let me try and replicate with a non-admin G Suite account as well :-) It could absolutely be something weird going on there as my normal "Free" account testing has been with a Gmail account so far.

RamblingCookieMonster commented 4 years ago

Weird! I'm not clear on what I'm doing wrong, but same deal with my personal free gmail account.

RamblingCookieMonster commented 4 years ago

Odd - noticed in New-GoogleService, right after you create $credential, $credential is null (janky write-verbose debugging), so HttpClientInitializer = $credential ends up not being super helpful. Not sure why this would happen though, sorry!

scrthq commented 4 years ago

Weird!! So it seems like there's something it's not liking with the $credential then? If you have some time tomorrow, we can step through on a screenshare and see where the pain is coming from

RamblingCookieMonster commented 4 years ago

Did some testing. In New-GoogleService, $credential is defined as:

$credential = [Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker]::AuthorizeAsync(
                        [Google.Apis.Auth.OAuth2.GoogleClientSecrets]::Load($stream).Secrets,
                        [string[]]$ClientSecretsScopes,
                        $User,
                        [System.Threading.CancellationToken]::None,
                        $(New-Object 'Google.Apis.Util.Store.FileDataStore' -ArgumentList $credPath,$true),
                        $(if ($PSVersionTable.PSVersion.Major -gt 5) {
                                New-Object 'Google.Apis.Auth.OAuth2.PromptCodeReceiver'
                            }
                            else {
                                New-Object 'Google.Apis.Auth.OAuth2.LocalServerCodeReceiver'
                            })
                    ).Result

When I look at [Google.Apis.Auth.OAuth2.GoogleClientSecrets]::Load($stream).Secrets, it shows only a ClientID property value, there is no ClientSecret value. If I add a ClientSecret value, it works.

I'm guessing this should be included in the OAuth 2.0 Client IDs json I downloaded. Perhaps Type: Desktop vs. Other is the problem? What do you select when picking a type now that Other isn't an option?

RamblingCookieMonster commented 4 years ago

Closing this out. For whatever reason, when i download the json for this oauth client ID, it does not include a client_secret value, as described here. Manually creating a client_secret property in the json with the value from the google oauth page got this up and running.

Sorry to be a pain, hopefully this helps if someone else runs into it!