Git Product home page Git Product logo

oauth2l's Introduction

oauth2l

oauth2l (pronounced "oauth tool") is a simple command-line tool for working with Google OAuth 2.0 written in Go. Its primary use is to fetch and print OAuth 2.0 access tokens, which can be used with other command-line tools and shell scripts.

Overview

oauth2l supports all Google OAuth 2.0 authentication flows for both user accounts and service accounts in different environments:

  • When running inside Google Compute Engine (GCE) and Google Kubernetes Engine (GKE), it uses the credentials of the current service account if it is available.

  • When running inside user context that has an active Google Cloud SDK (gcloud) session, it uses the current gcloud credentials.

  • When running with command option --credentials xxx, where xxx points to a JSON credential file downloaded from Google Cloud Console, oauth2l uses the file to start an OAuth session. The file can be either a service account key or an OAuth client ID.

  • When running with command option --type jwt --audience xxx and a service account key, a JWT token signed by the service account key will be generated.

  • When running with command option --type sso --email xxx, oauth2l invokes an external sso command to retrieve Single Sign-on (SSO) access token.

  • By default, retrieved tokens will be cached and stored in "~/.oauth2l". The cache location can be overridden via --cache xxx. To disable caching, set cache location to empty ("").

Quickstart

Pre-compiled binaries

Pre-built binaries are available for Darwin (Mac OS X), Linux, and Windows. You can download a build for any tag, for example:

OS Link
Darwin https://storage.googleapis.com/oauth2l/latest/darwin_amd64.tgz
Linux https://storage.googleapis.com/oauth2l/latest/linux_amd64.tgz
Windows https://storage.googleapis.com/oauth2l/latest/windows_amd64.tgz

Substitute "latest" for any tag version you'd like, removing any leading "v" prefix.

Homebrew (Mac OS X)

On Mac OS X, you can install oauth2l via Homebrew:

$ brew install oauth2l

Note that new releases may not be immediately available via Homebrew because updating is a manual process.

Docker

An official Docker image is available at:

gcr.io/oauth2l/oauth2l

You can run this directly:

$ docker run -it gcr.io/oauth2l/oauth2l header cloud-platform

Or use it to inject into an existing container:

FROM my-awesome-container
COPY --from gcr.io/oauth2l/oauth2l /bin/oauth2l /bin/oauth2l

Like the binary releases, the container images are tagged to match the repository tags (without the leading "v"). For master builds, use the "latest" tag.

Everywhere else

On other systems, you need to meet the following requirements to use this tool:

Minimum requirements:

  • The tool is only available for Linux or Mac
  • Go 1.10.3 or higher

Nice to have:

# Get the package from Github
$ git clone https://github.com/google/oauth2l
$ cd oauth2l

# Install the package into your $GOPATH/bin/
$ make dev

# Fetch the access token from your credentials with cloud-platform scope
$ ~/go/bin/oauth2l fetch --credentials ~/your_credentials.json --scope cloud-platform

# Or you can run if you $GOPATH/bin is already in your $PATH
$ oauth2l fetch --credentials ~/your_credentials.json --scope cloud-platform

Commands

fetch

Fetch and print an access token for the specified OAuth scopes. For example, the following command prints access token for the following OAuth2 scopes:

$ oauth2l fetch --scope userinfo.email,cloud-platform
ya29.zyxwvutsrqpnmolkjihgfedcba

header

The same as fetch, except the output is in HTTP header format:

$ oauth2l header --scope cloud-platform
Authorization: Bearer ya29.zyxwvutsrqpnmolkjihgfedcba

The header command is designed to be easy to use with the curl CLI. For example, the following command uses the PubSub API to list all PubSub topics.

$ curl -H "$(oauth2l header --scope pubsub)" https://pubsub.googleapis.com/v1/projects/my-project-id/topics

To send an API request using domain-wide delegation (DwD), for example, to list [email protected]'s Gmail labels:

$ curl -H "$(oauth2l header --email [email protected] --credentials service_account_credentials.json --scope https://www.googleapis.com/auth/gmail.labels)" https://gmail.googleapis.com/gmail/v1/users/me/labels

curl

This is a shortcut command that fetches an access token for the specified OAuth scopes and uses the token to make a curl request (via 'usr/bin/curl' by default). Additional flags after "--" will be treated as curl flags.

$ oauth2l curl --scope cloud-platform,pubsub --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics -- -i

To send an API request using domain-wide delegation (DwD), for example, to list [email protected]'s Gmail labels:

$ oauth2l curl --email [email protected] --credentials service_account_credentials.json --scope https://www.googleapis.com/auth/gmail.labels --url https://gmail.googleapis.com/gmail/v1/users/me/labels

info

Print information about a valid token. This always includes the list of scopes and expiration time. If the token has either the https://www.googleapis.com/auth/userinfo.email or https://www.googleapis.com/auth/plus.me scope, it also prints the email address of the authenticated identity.

$ oauth2l info --token $(oauth2l fetch --scope pubsub)
{
    "expires_in": 3599,
    "scope": "https://www.googleapis.com/auth/pubsub",
    "email": "[email protected]"
    ...
}

test

Test a token. This sets an exit code of 0 for a valid token and 1 otherwise, which can be useful in shell pipelines. It also prints the exit code.

$ oauth2l test --token ya29.zyxwvutsrqpnmolkjihgfedcba
0
$ echo $?
0
$ oauth2l test --token ya29.justkiddingmadethisoneup
1
$ echo $?
1

reset

Reset all tokens cached locally. We cache previously retrieved tokens in the file ~/.oauth2l by default.

$ oauth2l reset

web

Locally deploys and launches the OAuth2l Playground web application in a browser. If the web application packages are not yet installed, it will be installed under ~/.oauth2l-web by default. See Command Options section for all supported options for the web command.

Note that a local installation of Docker and docker-compose tool is required in order to support this feature. For most platforms, Docker can be installed by following the instructions here. For Google workstations, follow special installation procedures at "go/installdocker". The web feature is currently experimental and will be improved in the future.

$ oauth2l web

Command Options

--help

Prints help messages for the main program or a specific command.

$ oauth2l --help
$ oauth2l fetch --help

--credentials

Specifies an OAuth credential file (either an OAuth client ID or a Service Account key) to start the OAuth flow. You can download the file from Google Cloud Console.

$ oauth2l fetch --credentials ~/service_account.json --scope cloud-platform

If this option is not supplied, it will be read from the environment variable GOOGLE_APPLICATION_CREDENTIALS. For more information, please read Getting started with Authentication.

$ export GOOGLE_APPLICATION_CREDENTIALS="~/service_account.json"
$ oauth2l fetch --scope cloud-platform

When using an OAuth client ID file, the following applies:

If the first redirect_uris in the --credentials client_id.json is set to urn:ietf:wg:oauth:2.0:oob, the 3LO out of band flow is activated. NOTE: 3LO out of band flow has been deprecated and will stop working entirely in Oct 2022.

If the first redirect_uris in the --credentials client_id.json is set to http://localhost[:PORT], the 3LO loopback flow is activated. When the port is omitted, an available port will be used to spin up the localhost. When a port is provided, oauth2l will attempt to use such port. If the port cannot be used, oauth2l will stop.

--type

The authentication type. The currently supported types are "oauth", "jwt", or "sso". Defaults to "oauth".

oauth

When oauth is selected, the tool will fetch an OAuth access token through one of two different flows. If service account key is provided, 2-legged OAuth flow is performed. If OAuth Client ID is provided, 3-legged OAuth flow is performed, which requires user consent. Learn about the different types of OAuth here.

$ oauth2l fetch --type oauth --credentials ~/client_credentials.json --scope cloud-platform

jwt

When jwt is selected and the json file specified in the --credentials option is a service account key file, a JWT token signed by the service account private key will be generated. Either --audience or --scope must be specified for this option. See how to construct the audience here.

  • With audience:

    $ oauth2l fetch --type jwt --credentials ~/service_account.json --audience https://pubsub.googleapis.com/
  • With scope:

    $ oauth2l fetch --type jwt --credentials ~/service_account.json --scope cloud-platform

sso

When sso is selected, the tool will use an external Single Sign-on (SSO) CLI to fetch an OAuth access token. The default SSO CLI only works with Google's corporate SSO. An email is required in addition to scope.

To use oauth2l with the default SSO CLI:

$ oauth2l header --type sso --email [email protected] --scope cloud-platform

To use oauth2l with a custom SSO CLI:

$ oauth2l header --type sso --ssocli /usr/bin/sso --email [email protected] --scope cloud-platform

Note: The custom SSO CLI should have the following interface:

$ /usr/bin/sso [email protected] scope1 scope2

--scope

The scope(s) that will be authorized by the OAuth access token. Required for oauth and sso authentication types. When using multiple scopes, provide the the parameter as a comma-delimited list and do not include spaces. (Alternatively, multiple scopes can be specified as a space-delimited string surrounded in quotes.)

$ oauth2l fetch --scope cloud-platform,pubsub

--sts

If true, exchanges the fetched access token with an STS token using Google's Secure Token Service. You may optionally specify claims to be embedded into the STS token. The currently supported STS claims are "audience" and "quota_project".

This option is compatible with oauth and sso authentication types, but is currently incompatible with jwt.

$ oauth2l fetch --sts --audience https://pubsub.googleapis.com/ --quota_project quotaprojectid

--audience

The single audience to include in the signed JWT token. Required for jwt authentication type. Can also be used for STS.

$ oauth2l fetch --type jwt --audience https://pubsub.googleapis.com/

--quota_project

The quota project to include in the STS claim. Used for quota and billing override.

$ oauth2l fetch --sts --quota_project quotaprojectid

--email

The email associated with SSO. Required for sso authentication type.

$ oauth2l fetch --type sso --email [email protected] --scope cloud-platform

The email parameter can be also used to specify a user email account for domain-wide delegation when authenticating with Service Account credentials.

$ oauth2l fetch --credentials ~/service_account.json --scope cloud-platform --email [email protected]

--ssocli

Path to SSO CLI. For optional use with "sso" authentication type.

$ oauth2l fetch --type sso --ssocli /usr/bin/sso --email [email protected] --scope cloud-platform

--cache

Path to token cache file. Disables caching if set to empty (""). Defaults to ~/.oauth2l if not configured.

$ oauth2l fetch --cache ~/different_path/.oauth2l --scope cloud-platform

--refresh

If true, attempt to refresh expired access token (from the cache) using refresh token instead of re-authorizing.

$ oauth2l fetch --credentials ~/client_credentials.json --scope cloud-platform --refresh

--impersonate-service-account

If specified, exchanges the fetched User access token with a Service Account access token using Google's IAM Service. The Service Account parameter can be specified as an ID or an email. Note that at least one of "cloud-platform" or "iam" must be included in the scope parameter. Learn more about Service Account Impersonation here.

$ oauth2l fetch --credentials ~/client_credentials.json --scope cloud-platform,pubsub --impersonate-service-account 113258942105700140798

--disableAutoOpenConsentPage

Disables the feature to automatically open the consent page in 3LO loopback flows. When this option is used, the user will be provided with a URL to manually interact with the consent page. This flag does not take any arguments. Simply add the option to disable this feature.

$ oauth2l fetch --credentials ~/client_credentials.json --disableAutoOpenConsentPage --consentPageInteractionTimeout 60 --consentPageInteractionTimeoutUnits seconds --scope cloud-platform

--consentPageInteractionTimeout

Amount of time to wait for a user to interact with the consent page in 3LO loopback flows. Once the time has lapsed, the localhost at the redirect_uri will no longer be available.
Its default value is 2. See --consentPageInteractionTimeoutUnits to change the units.

--consentPageInteractionTimeoutUnits

Units of measurement to use when --consentPageInteractionTimeout is set. Its default value is minutes. Valid inputs are seconds and minutes. This option only affects 3LO loopback flows.

fetch --output_format

Token's output format for "fetch" command. One of bare, header, json, json_compact, pretty, or refresh_token. Default is bare.

$ oauth2l fetch --output_format pretty --scope cloud-platform

curl --url

URL endpoint for curl request. Required for "curl" command.

$ oauth2l curl --scope cloud-platform --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics

curl --curlcli

Path to curl CLI. For optional use with "curl" command.

$ oauth2l curl --curlcli /usr/bin/curl --type sso --email [email protected] --scope cloud-platform --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics

web --stop

Stops the OAuth2l Playground web app.

$ oauth2l web --stop

web --directory

Installs OAuth2l-web packages to a specfic directory. If this option is used, it should be provided again for future executions of the web command, such as stopping and restarting the web app.

$ oauth2l web --directory your/new/directory

Previous Version

The previous version of oauth2l was written in Python and it is located at the python directory. The Python version is deprecated because it depends on a legacy auth library and contains some features that are no longer best practice. Please switch to use the Go version instead.

oauth2l's People

Contributors

0o001 avatar 4z3 avatar andyrzhao avatar aurkenb avatar bboughton avatar bochunz avatar craigcitro avatar eesheesh avatar ericsmekens avatar itsstrobe avatar kerneis avatar leeeoooo3 avatar mahiuchun avatar sdenef-adeo avatar sethvargo avatar shinfan avatar spothala avatar thiagowfx avatar timdp avatar ulisesl avatar wcn3 avatar wora avatar zagrodzki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

oauth2l's Issues

go get error

This is what i get when i run the go get coomand

git pull --ff-only
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

git branch --set-upstream-to=<remote>/<branch> master

FR: output gcloud-style refresh token credentials

Currently everything looks pretty oriented around access tokens. It'd be nice to be able to get refresh tokens, too, preferably in the format gcloud uses:

$ cat ~/.config/gcloud/application_default_credentials.json 
{
  "client_id": "32555940559.apps.googleusercontent.com",
  "client_secret": "ZmssLNjJy2998hD4CTg2ejr2",
  "refresh_token": "xxxredacted",
  "type": "authorized_user"
}

I looked through the code to see whether it's feasible to add this to the "fetch" command but I don't think so, it seems like it'd need to be a separate sub-command.

Improve handling of expired access tokens in cache.

oauth2l currently does not invalidate or refresh expired access tokens in the cache, so after one-hour, manual cache "reset" is required to clear the expired access token. Furthermore, when manually resetting cached tokens, even the non-expired tokens are lost. This leads to having to log in many times for 3LO flow.

This problem should be addressed at two levels:

  1. Automatically invalidating expired access tokens, without requiring manual "reset".
  2. If possible, automatically refresh expired 3lo oauth2 access token, via the refresh token.

When pip install --user, there is conflict with older version of six

When I pip install --user google-oauth2l,

Downloading six-1.10.0-py2.py3-none-any.whl
...
Successfully installed google-apitools-0.5.4 google-oauth2l-0.8.0 httplib2-0.9.2 oauth2client-2.1.0 pyasn1-0.1.9 pyasn1-modules-0.0.8 rsa-3.4.2 setuptools-1.1.6 six-1.4.1

For some reason, six-1.4.1 is in the system somewhere.

oauth2l says result of `oauth2l fetch --scope userinfo.email` is invalid

The following behavior is unexpected and contrary to the README's example

$ oauth2l info --token $(oauth2l fetch --scope userinfo.email)
{
 "error_description": "Invalid Value"
}

I'm signed in using gcloud auth application-default login.

This is also the case for scopes email and openid. The token generated is considered valid if I fully specify the scope as shown:

$ oauth2l info --token $(oauth2l fetch --scope https://www.googleapis.com/auth/userinfo.email)
{
 ...
 "scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/accounts.reauth openid",
 ...
}

Glancing through the issue tracker, this looks related to #71, but I'm using the oauth2l downloaded from https://storage.googleapis.com/oauth2l/1.0.2/linux_amd64.tgz so it should include the change fixing that issue.

Cannot install oauth2l in Google Cloud Shell out of the box

A default Google Cloud Shell environment cannot install oauth2l. Attempting to do so results in the following:
$ pip install google-oauth2l Collecting google-oauth2l Downloading https://files.pythonhosted.org/packages/4a/a2/270bf3e7755a394bd724dd21f65775b9f002bd2459f5767887935564ff35/google_oauth2l-1.0.2-py2.py3-none-any.whl Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python2.7/dist-packages (from google-oauth2l) (40.0.0) Collecting fasteners>=0.14.1 (from google-oauth2l) Downloading https://files.pythonhosted.org/packages/14/3a/096c7ad18e102d4f219f5dd15951f9728ca5092a3385d2e8f79a7c1e1017/fasteners-0.14.1-py2.py3-none-any.whl Requirement already satisfied: oauth2client>=2.1.0 in /usr/local/lib/python2.7/dist-packages (from google-oauth2l) (4.1.2) Collecting pyopenssl>=17.5.0 (from google-oauth2l) Downloading https://files.pythonhosted.org/packages/96/af/9d29e6bd40823061aea2e0574ccb2fcf72bfd6130ce53d32773ec375458c/pyOpenSSL-18.0.0-py2.py3-none-any.whl (53kB) 100% |████████████████████████████████| 61kB 6.1MB/s Requirement already satisfied: httplib2>=0.9.1 in /usr/local/lib/python2.7/dist-packages (from google-oauth2l) (0.11.3) Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python2.7/dist-packages (from google-oauth2l) (1.11.0) Collecting monotonic>=0.1 (from fasteners>=0.14.1->google-oauth2l) Downloading https://files.pythonhosted.org/packages/ac/aa/063eca6a416f397bd99552c534c6d11d57f58f2e94c14780f3bbf818c4cf/monotonic-1.5-py2.py3-none-any.whl Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python2.7/dist-packages (from oauth2client>=2.1.0->google-oauth2l) (3.4.2) Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python2.7/dist-packages (from oauth2client>=2.1.0->google-oauth2l) (0.2.2) Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python2.7/dist-packages (from oauth2client>=2.1.0->google-oauth2l) (0.4.3) Collecting cryptography>=2.2.1 (from pyopenssl>=17.5.0->google-oauth2l) Downloading https://files.pythonhosted.org/packages/67/21/e79987f1f9abae42d666b1f89b4e78aa096acc00bbf97ad40d19b07b4a83/cryptography-2.3-cp27-cp27mu-manylinux1_x86_64.whl (2.1MB) 100% |████████████████████████████████| 2.1MB 6.2MB/s Requirement already satisfied: enum34; python_version < "3" in /usr/local/lib/python2.7/dist-packages (from cryptography>=2.2.1->pyopenssl>=17.5.0->google-oauth2l) (1.1.6) Requirement already satisfied: idna>=2.1 in /usr/local/lib/python2.7/dist-packages (from cryptography>=2.2.1->pyopenssl>=17.5.0->google-oauth2l) (2.7) Collecting cffi!=1.11.3,>=1.7 (from cryptography>=2.2.1->pyopenssl>=17.5.0->google-oauth2l) Downloading https://files.pythonhosted.org/packages/14/dd/3e7a1e1280e7d767bd3fa15791759c91ec19058ebe31217fe66f3e9a8c49/cffi-1.11.5-cp27-cp27mu-manylinux1_x86_64.whl (407kB) 100% |████████████████████████████████| 409kB 17.1MB/s Collecting asn1crypto>=0.21.0 (from cryptography>=2.2.1->pyopenssl>=17.5.0->google-oauth2l) Downloading https://files.pythonhosted.org/packages/ea/cd/35485615f45f30a510576f1a56d1e0a7ad7bd8ab5ed7cdc600ef7cd06222/asn1crypto-0.24.0-py2.py3-none-any.whl (101kB) 100% |████████████████████████████████| 102kB 20.9MB/s Collecting ipaddress; python_version < "3" (from cryptography>=2.2.1->pyopenssl>=17.5.0->google-oauth2l) Downloading https://files.pythonhosted.org/packages/fc/d0/7fc3a811e011d4b388be48a0e381db8d990042df54aa4ef4599a31d39853/ipaddress-1.0.22-py2.py3-none-any.whl Collecting pycparser (from cffi!=1.11.3,>=1.7->cryptography>=2.2.1->pyopenssl>=17.5.0->google-oauth2l) Downloading https://files.pythonhosted.org/packages/8c/2d/aad7f16146f4197a11f8e91fb81df177adcc2073d36a17b1491fd09df6ed/pycparser-2.18.tar.gz (245kB) 100% |████████████████████████████████| 256kB 18.9MB/s Building wheels for collected packages: pycparser Running setup.py bdist_wheel for pycparser ... done Stored in directory: /home/michael_olson/.cache/pip/wheels/c0/a1/27/5ba234bd77ea5a290cbf6d675259ec52293193467a12ef1f46 Successfully built pycparser tensorflow 1.9.0 has requirement setuptools<=39.1.0, but you'll have setuptools 40.0.0 which is incompatible. Installing collected packages: monotonic, fasteners, pycparser, cffi, asn1crypto, ipaddress, cryptography, pyopenssl, google-oauth2l Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/monotonic.pyc' Consider using the --user option or check the permissions.

The install fails because tensorflow requires a lower version of setuptools than Google Cloud Shell ships with. If tensorflow can be trimmed from the oauth2l dependencies, that's probably ideal.

It may also be worth considering having oauth2l installed by default in Google Cloud Shell.

Support id_token for JWT path

I tried to generate an id_token to test Google Cloud Run, but

oauth2l fetch --type=jwt  --audience="https://hello-my-cloud-run.a.run.app" --credentials=$HOME/Documents/my-service-account-private-key.json --output_format=json
{
  "access_token": ".......",
  "expiry": "2021-07-28T01:07:05.242408872-07:00",
  "token_type": "Bearer"
}

It only outputs the access_token, but no id_token.

I tried this token in curl against my cloud run url and got error:

< www-authenticate: Bearer error="invalid_token" error_description="The access token could not be verified"

syntax error in linux pre-compiled binary

Trying to install on ARMv7 BusyBox (router) using the pre-compiled binary.

Downloaded, decompressed and set as executable with chmod +x oauth2l.

Upon running the tool though, I get ./oauth2l: line 2: syntax error: unterminated quoted string

Support Service Account Impersonation

We would like to support service account impersonation, which allows users to exchange access tokens to act as service accounts.

The command may look like:

oauth2l fetch --scope cloud-platform --impersonated-service-account [SERVICE_ACCOUNT]

The command will return a short-term access token to act as the service account specified.

Implementation wise, this command will call the IAM generateAccessToken API method.

We should also consider supporting the reverse - "service account impersonating user account".

error with go 1.12 and go modules

'''
$ mkdir tooltest
ptone-macbookpro:tmp$ cd tooltest/
ptone-macbookpro:tooltest$ go mod init main
go: creating new go.mod: module main
ptone-macbookpro:tooltest$ go get github.com/google/oauth2l
ptone-macbookpro:tooltest$ go install github.com/google/oauth2l
can't load package: package github.com/google/oauth2l: unknown import path "github.com/google/oauth2l": cannot find module providing package github.com/google/oauth2l
'''

go version: go version go1.12.1 darwin/amd64

Segfault on MACOS Monterey

I've tried reinstalling it and deleting all the local configs but without success. Tested with the latest master commit and the version available through homebrew.

➜  Desktop uname -a                                                                                                                                                                                   ~/Desktop
Darwin ************* 21.6.0 Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64 x86_64 i386 Darwin
➜  Desktop oauth2l fetch --scope=https://mail.google.com/ --refresh                                                                                                                                   ~/Desktop
panic: runtime error: invalid memory address or nil pointer dereference


[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x12a7609]

goroutine 1 [running]:
github.com/google/oauth2l/util.authorization3LOLoopback({0xc0001c0000, 0x13c}, {0xf4?, 0x9?}, 0xc000075f70)
        /private/tmp/oauth2l-20220720-4107-1ir1j37/oauth2l-1.3.0/util/auth-handlers.go:78 +0x49
github.com/google/oauth2l/util.Get3LOAuthorizationHandler.func1({0xc0001c0000, 0x13c})
        /private/tmp/oauth2l-20220720-4107-1ir1j37/oauth2l-1.3.0/util/auth-handlers.go:39 +0x13d
golang.org/x/oauth2/authhandler.authHandlerSource.Token({{0x13d5f48, 0xc0000160b8}, 0xc00019d030, 0xc0001a06f0, {0x1345eac, 0x5}, 0xc0001a0960})
        /private/tmp/oauth2l-20220720-4107-1ir1j37/oauth2l-1.3.0/vendor/golang.org/x/oauth2/authhandler/authhandler.go:80 +0x1b6
golang.org/x/oauth2.(*reuseTokenSource).Token(0xc00007e760)
        /private/tmp/oauth2l-20220720-4107-1ir1j37/oauth2l-1.3.0/vendor/golang.org/x/oauth2/oauth2.go:304 +0xd5
github.com/google/oauth2l/util.FetchToken({0x13d5f48?, 0xc0000160b8?}, 0x8?)
        /private/tmp/oauth2l-20220720-4107-1ir1j37/oauth2l-1.3.0/util/fetch.go:62 +0xdd
github.com/google/oauth2l/util.fetchToken(0xc0000d6370, 0xc00019ccb0)
        /private/tmp/oauth2l-20220720-4107-1ir1j37/oauth2l-1.3.0/util/tasks.go:187 +0x1bc
github.com/google/oauth2l/util.Fetch(0x1345eac?, 0xc00019ccb0)
        /private/tmp/oauth2l-20220720-4107-1ir1j37/oauth2l-1.3.0/util/tasks.go:79 +0x25
main.main()
        /private/tmp/oauth2l-20220720-4107-1ir1j37/oauth2l-1.3.0/main.go:426 +0x16a8

Remove default oauth client id

The default client id has few APIs enabled, very little quota and no billing. It is not useful for any practical purpose. We should remove it and ask developers to use their own client id, so they can see the logging and monitoring in Google API Console.

Note: oauth2l is for developers to test APIs, it is not a convenient tool for end users.

Oneplatform/sso: no such file or directory

I try to auth via sso, but have errors:

oauth2l header --type sso --email [email protected] --scope cloud-platform
fork/exec /google/data/ro/teams/oneplatform/sso: no such file or directory
Failed to fetch SSO token

Installed by homebrew. Where I can get oneplatform/sso?

advice for installing on Cent OS 6.10?

Any advice for installing in centos 6.10?

pip install google-oauth2l
Traceback (most recent call last):
File "/usr/bin/pip", line 5, in
from pkg_resources import load_entry_point
File "/usr/lib/python2.6/site-packages/setuptools-40.0.0-py2.6.egg/pkg_resources/init.py", line 72, in
from . import py31compat
File "/usr/lib/python2.6/site-packages/setuptools-40.0.0-py2.6.egg/pkg_resources/py31compat.py", line 18, in
sys.version_info.major == 2 or
AttributeError: 'tuple' object has no attribute 'major'

--scope requires different input on windows/linux

Hello! When running oauth2l on windows I can specify scope like this:
oauth2l fetch --credentials a.json --scope userinfo.email
and successfuly receive a token

whereas running oauth2l on linux I have to specify full scope like this:
oauth2l fetch --credentials a.json --scope https://www.googleapis.com/auth/userinfo.email
otherwise I'll get following error:

$ oauth2l fetch --credentials a.json --scope userinfo.email
oauth2: cannot fetch token: 400 Bad Request
Response: {"error":"invalid_scope","error_description":"Invalid OAuth scope or ID token audience provided."}

For your consideration:
Maybe it's worth to update the documentation to mention such a feature?

Clean install of oauth2l in docker container produces scope error

Try the following sequence in docker on mac os x:

1 apt-get update
2 apt-get install python2.7
3 python2.7 get-pip.py
4 pip install google-oauth2l
5 oauth2l fetch cloud-platform

Got the following error:

Successfully built oauth2client httplib2
Installing collected packages: six, httplib2, pyasn1, pyasn1-modules, rsa, oauth2client, google-apitools, google-oauth2l
Successfully installed google-apitools-0.5.4 google-oauth2l-0.8.0 httplib2-0.9.2 oauth2client-2.1.0 pyasn1-0.1.9 pyasn1-modules-0.0.8 rsa-3.4.2 six-1.10.0
root@17df79961545:~# oauth2l fetch cloud-platform
Error encountered in fetch operation: 'NoneType' object has no attribute 'create_scoped'

Consider binary compression

Version 1.3.0 for x64 Linux weighs in at 5.8 MB. While that's not huge, running it through UPX with default settings brings it down to 2.3 MB, a whopping 60% reduction. This seems like a fairly trivial improvement that could be incorporated into the Makefile. Thoughts?

Invalid JWT: Failed audience check.

Hi! I genarated a JWT code with:
oauth2l fetch --type jwt --credentials my-service-account-file.json --scope firebase.messaging
Then request access_token with CURL like this:
curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=<JWT_CODE> ' https://oauth2.googleapis.com/token
but got 400 Bad Request: Invalid JWT: Failed audience check.

And with the JWT code genarated from
oauth2l fetch --type jwt --credentials ./my-service-account-file.json --audience https://oauth2.googleapis.com/token, I got the 400 Bad Request error
"error": "invalid_scope", "error_description": "Invalid OAuth scope or ID token audience provided."

Are there any arguments that I missed?

No web proxy support

We have an environment where we need to access the Internet via proxy, but unfortunately, the tool does not support this setup. Is it complicated to add proxy support using some standard environment variable like HTTP_PROXY?

Enter authorization code:

Hi.
I installed auth2l to my MacOs.
When I trying to fetch access token I got message "Enter authorization code"
Where I can take that code ?

image

oauth token now contains trailing dots

Recently tokens returned from fetch are different than tokens I've retrieved in the past. The tokens are now right padded with dots.

example:

ya29.c.<long-string>...............................................................................

Is this intended and are the dots part of the actual token?

parse error: asn1: syntax error: sequence truncated

Hello im trying to fetch a google api token for the postmaster tools but i have some errors using the script;

using it directly with the credentials.json download from the google console i have received;

$ ./oauth2l fetch --credentials credentials.json --scope postmaster.readonly
missing 'type' field in credentials
$

Adding "type":"service_account","web" to the json file the error have changed for the following;

$ ./oauth2l fetch --credentials credentials.json --scope postmaster.readonly
private key should be a PEM or plain PKCS1 or PKCS8; parse error: asn1: syntax error: sequence truncated
$

Whats about is the last one related ?,

Thanks

sgauth.Settings to accept credentials.Credentials

I'm trying to understand if oauth2l is primarily supposed to be exec'd out to, to get credentials –or it's supposed to be imported as a Go package (given, I'm using Go).

In that case, I think it would be better to allow sgauth.Settings.CredentialsJSON object to be replaced with a *credentials.Credentials field, as I might be hardcoding the client_id, client_secret etc in my program, or reading from env, etc. I'm assuming the schema of the creds JSON file isn't used to determine the auth format?

I'm trying to implement a tool to do 3LO and it does not seem like there's a clear API surface provided by this repo. I'm assuming this tool is supposed to be exec'd into so maybe I'm doing this wrong.

Step: Go to the following link in your browser

I notice that this step is achieved by somehow telling the OAuth2 servers not to use a redirect URI, but to instead return the verification code to the screen. Is there any way to make this step automatic? Can the library temporarily open a HTTP server and direct the callback to it so that it can authenticate without multiple manual copy-paste's by the user?

Publish to github releases API with goreleaser?

I'm just wondering if you'd consider publishing to github releases.

I'd like to get oauth2l up on https://webinstall.dev and although the current XML API version looks very sane, it would be nice to not have to write custom code and just use the Github Releases API - since this seems to be canonically hosted on Github anyway.

Unable to get interactive auth flow from "oauth2 fetch --type=oauth"

Hi, thanks for this cool tool!

I'm trying to see if I can build a command-line tool that authenticates to Google APIs using the auth model used by gcloud, which involves user to click to a browser URL and go to a localhost:8080 callback url, or something like user copying the token back to the CLI tool.

I've been trying to see if oauth2l can provide interactive input (#61 claims it can). But when I try this, it doesn't work:

$ oauth2l fetch --type=oauth --scope cloud-platform
google: could not find default credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

I'm curious if there's a code sample in this repo about that.

Consider printing 3LO messages to stderr

When the oauth2l command is embedded in bash alias, such as

alias gcurl='curl -H "$(oauth2l header --json ~/client_secret.json cloud-platform userinfo.email)" -H "Content-Type: application/json"'

printing to stdout swallows the message, and the user won't know oauth2l is requesting a web authorization.

oauth2l is unnecessarily interactive, which gets in the way of automation

Why does oauth2l fetch print the url and then wait for user input forever for scopes like admin.directory.user ?

Sure, you can do something like oauth2l fetch ... </dev/null|grep -m1 -o 'https://.*' to get the url and then echo "$code"|oauth2l fetch ..., but why are we forced to scrape stdout from a command line tool ? And then you have to specially handle the exit code from the first step if you want to catch genuine errors (or if you just want to prevent the whole script from failing in the presence of set -eEo pipefail).

None of this fiddling would be necessary if this was split into two separate non-interactive operations, instead of a single interactive one. There's plenty of cases where inputs can only be provided at the beginning of an automated process and currently oauth2l is unnecessarily painful to use in such cases.

Add more key supports in Go version

The Go version currently only support json key files, we need to support

  • getting token using GAE/GCE metadata service
  • getting token from gcloud CLI installed locally
  • getting key file from environment variables

Cannot get token for Google Photos

I have created an app in the Google Cloud Console and downloaded the OAuth client JSON file. oauth2l complains that the key has no type field. While searching I found that some users got around this by using a service account instead but service accounts are not supported by the Photos API. README says that --credentials can be a OAuth client.

PS C:\Users\gabbsmo> oauth2l.exe fetch --scope photoslibrary.readonly --credentials "D:\Downloads\client_secret_xxx.apps.googleusercontent.com.json"
missing 'type' field in credentials

Generate jwt for users

--jwt seems to be only supported for serviceaccounts, how, if at all, can we generate a JWT for authenticated humans?

Service Account flow - 2 Legged Oauth Golang

I know possibly this isn't the apt place for this question

I want to get the Oauth token from the GCP client credentials.
Reference

Works well with oauth2l fetch --credentials ~/Downloads/esp-rainmaker-97663-2f539a842d10.json --scope https://www.googleapis.com/auth/homegraph

When I try with the Golang API, I get the following error.

package main

import (
	"fmt"
	"io/ioutil"
	"log"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
)

func main() {
	data, err := ioutil.ReadFile("/Users/supreetdeshpande/Downloads/esp-rainmaker-97663-2f539a842d10.json")
	if err != nil {
		log.Fatal(err)
	}
	conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/homegraph")
	if err != nil {
		log.Fatal(err)
	}

	client := conf.Client(oauth2.NoContext)
	response, err := client.Get("...")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(response)
}

I have downloaded the credentials and they work well with the Google Actions Test suite.
I tried this code but I'm getting 2020/06/02 01:58:56 Get ...: unsupported protocol scheme ""

Often these errors seem to arise due to incorrect token URLs. My configured URI is https://oauth2.googleapis.com/token which conforms as stated here.

To confirm the scheme I replaced ("...") above with the actual URL,
response, err := client.Get("https://oauth2.googleapis.com/token")
It resulted in the below error,

&{404 Not Found 404 HTTP/2.0 2 0 map[Alt-Svc:[h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"] Content-Length:[0] Content-Type:[text/html] Date:[Tue, 02 Jun 2020 18:43:01 GMT] Server:[scaffolding on HTTPServer2] X-Content-Type-Options:[nosniff] X-Frame-Options:[SAMEORIGIN] X-Xss-Protection:[0]] {0xc0002a6280} 0 [] false false map[] 0xc00011e300 0xc0000b2370}

Snippet from the JSON file - "token_uri": "https://oauth2.googleapis.com/token", Tried printing the client before the Get call and it did print the correct URL too.

Is there something I could be missing?

no longer receiving identity token

I know this isn't the best place to post this, but I'm not sure where else to start out.

At some point in the past [ 6 months + ] I could use oauth2l with my GCP project and out would come an id_token field when I requested with OIDC scopes e.g.

$ oauth2l fetch --scope='openid,email,profile' --type=oauth --output_format=json

would produce JSON with an id_token field.

Now when I run oauth2l version 1.2.0 for the same project, I only see the following fields:

  • access_token
  • expiry
  • refresh_token
  • token_type

Is this a change in oauth2l? a change with GCP Auth? Maybe something with my account? Any help in tracking down the issue would be appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.