Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applications.

Overview

Goth: Multi-Provider Authentication for Go GoDoc Build Status Go Report Card

Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applications.

Unlike other similar packages, Goth, lets you write OAuth, OAuth2, or any other protocol providers, as long as they implement the Provider and Session interfaces.

This package was inspired by https://github.com/intridea/omniauth.

Installation

$ go get github.com/markbates/goth

Supported Providers

  • Amazon
  • Apple
  • Auth0
  • Azure AD
  • Battle.net
  • Bitbucket
  • Box
  • Cloud Foundry
  • Dailymotion
  • Deezer
  • DigitalOcean
  • Discord
  • Dropbox
  • Eve Online
  • Facebook
  • Fitbit
  • Gitea
  • GitHub
  • Gitlab
  • Google
  • Google+ (deprecated)
  • Heroku
  • InfluxCloud
  • Instagram
  • Intercom
  • Kakao
  • Lastfm
  • Linkedin
  • LINE
  • Mailru
  • Meetup
  • MicrosoftOnline
  • Naver
  • Nextcloud
  • Okta
  • OneDrive
  • OpenID Connect (auto discovery)
  • Oura
  • Paypal
  • SalesForce
  • Shopify
  • Slack
  • Soundcloud
  • Spotify
  • Steam
  • Strava
  • Stripe
  • Tumblr
  • Twitch
  • Twitter
  • Typetalk
  • Uber
  • VK
  • Wepay
  • Xero
  • Yahoo
  • Yammer
  • Yandex

Examples

See the examples folder for a working application that lets users authenticate through Twitter, Facebook, Google Plus etc.

To run the example either clone the source from GitHub

$ git clone [email protected]:markbates/goth.git

or use

$ go get github.com/markbates/goth
$ cd goth/examples
$ go get -v
$ go build
$ ./examples

Now open up your browser and go to http://localhost:3000 to see the example.

To actually use the different providers, please make sure you set environment variables. Example given in the examples/main.go file

Security Notes

By default, gothic uses a CookieStore from the gorilla/sessions package to store session data.

As configured, this default store (gothic.Store) will generate cookies with Options:

&Options{
   Path:   "/",
   Domain: "",
   MaxAge: 86400 * 30,
   HttpOnly: true,
   Secure: false,
 }

To tailor these fields for your application, you can override the gothic.Store variable at startup.

The following snippet shows one way to do this:

key := ""             // Replace with your SESSION_SECRET or similar
maxAge := 86400 * 30  // 30 days
isProd := false       // Set to true when serving over https

store := sessions.NewCookieStore([]byte(key))
store.MaxAge(maxAge)
store.Options.Path = "/"
store.Options.HttpOnly = true   // HttpOnly should always be enabled
store.Options.Secure = isProd

gothic.Store = store

Issues

Issues always stand a significantly better chance of getting fixed if they are accompanied by a pull request.

Contributing

Would I love to see more providers? Certainly! Would you love to contribute one? Hopefully, yes!

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Write Tests!
  4. Make sure the codebase adhere to the Go coding standards by executing gofmt -s -w ./
  5. Commit your changes (git commit -am 'Add some feature')
  6. Push to the branch (git push origin my-new-feature)
  7. Create new Pull Request
Issues
  • Added support for Microsoft Online

    Added support for Microsoft Online

    • Added support for V2 of Microsoft Online OAuth2 API which can be used for Microsoft personal accounts.
    • Small fixes in AzureAD provider
    • Updated example suit

    To test, application needs to be registered in Application Registration Portal

    opened by michalpristas 34
  • Added Refresh Token/Expiry Date of Access Token for applicable providers

    Added Refresh Token/Expiry Date of Access Token for applicable providers

    Hi Mark, I have Added Refresh Token/Expiry Date of Access Token for applicable providers. There is a change in provider interface where we have additional methods :

    • RefreshToken(refreshToken string) (*oauth2.Token, error) //Get new access token based on the refresh token
    • RefreshTokenAvailable()(bool) //Refresh token is provided by auth provider or not

    I have implemented and tested these for all existing providers.

    Kindly review and see if we can merge it to the master.

    Thanks, Rakesh Goyal

    opened by rakesh-eltropy 17
  • Replace direct usage of http.DefaultClient in providers and oauth2 calls

    Replace direct usage of http.DefaultClient in providers and oauth2 calls

    Some providers already used a custom httpClient. This brings the Client field to all providers and uses a fallback method to provide the http.DefaultClient if no client is set.

    This also uses the custom httpClient for the oauth2 calls via the context.

    The change should allow better inversion of control during unit tests by providing a custom client.

    I also ran go format on some files to clean up the import statements.

    opened by felixLam 16
  • Why logout after completing user auth?

    Why logout after completing user auth?

    This line was breaking authentication for me when utilizing any store. What is the purpose of this line?

    https://github.com/markbates/goth/blob/6c3a31e5f6aa001e8c3d6cec3f65d5bcc0240e69/gothic/gothic.go#L150

    opened by terev 15
  • Add support for defining Github scopes to the Github provider

    Add support for defining Github scopes to the Github provider

    I'm not sure your preference on things like this and your testing style (single assert per test case, etc...).

    This is a quick pass implemented to maintain backwards compatibility by extending the existing github provider api to allow for adding scopes before beginning the auth process.

    The New() function could also be extended to take a scopes []string param, but that would break the API for all current users.

    Close #20

    opened by cpjolicoeur 13
  • gothic fails when auth provider responds with URL fragments

    gothic fails when auth provider responds with URL fragments

    I'm using Facebook auth, and specified response_type=code%20token in my auth request (as described here), which results in FaceBook responding with a URL fragment, which breaks gothic and results in the following error from the verification phase:

    ERROR: oauth2: cannot fetch token: 400 Bad Request Response: {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}
    

    It appears that gothic is not parsing the URL response from FaceBook, and ends up with an empty url.Values map.

    To be clear, this happens when I bypass BeginAuthHandler() and handle that phase of the auth workflow myself.

    So ideally, it would be handy if there were some way to get BeginAuthHandler() to (optionally, of course) specify the response_type for FaceBook (and possibly other providers, if they support that type of operation).

    Improvement frozen due to age 
    opened by flimzy 11
  • Support for refresh tokens

    Support for refresh tokens

    Generated access tokens most likely have an expiration date. Would it be acceptable to add support for refresh tokens and their expiration date along with a flow to refresh them?

    opened by bryanl 10
  • Support multiple instances of one provider type

    Support multiple instances of one provider type

    To be able to register the same provider twice we need to be able to override the provider name. Don't want this to be a new func registered to the provider.Name but be inline with Client ( #123 ) Downside is that existing calls to provider.Name() will break (easy to replace with GetName() )

    This will maybe also fix issue #126 ?

    opened by willemvd 9
  • Set

    Set "access_type=offline" to google provider as default

    I set access_type=offline as default, referring to https://github.com/markbates/goth/pull/315#issuecomment-590389528

    Related PRs: https://github.com/markbates/goth/pull/347 https://github.com/markbates/goth/pull/315

    opened by shiwano 8
  • Example code failure: could not find a matching session for this request

    Example code failure: could not find a matching session for this request

    When running the example code with the linkedin provider (or any provider) I get the error could not find a matching session for this request. After doing a bit of debugging I found that the only way the example works is if I remove the defer in CompletUserAuth handler.

    I could completely be missing something but it appears as though every time we successfully auth and add the data to the session we are logging out and removing is. Is this intended behavior? What am I missing?

    Any help you can provide would be greatly appreciated.

    opened by lsiv568 8
  • Seeing

    Seeing "OK" text with link when successfully authenticated on GPlus

    Hi,

    I really love this library, works great. One small issue I'm facing is if a user is already logged in, they see a screen where it says "OK" with a link to the redirect URL. I'd like to get rid of this and redirect to the redirection URL immediately if a user is already logged in. Would really appreciate any help.

    Thanks, Faraz

    frozen due to age 
    opened by farazfazli 8
  • setting state when using google

    setting state when using google

    Hi, I am using goth to handle google SSO login but I am confused how should I set a state so that I can get back the state value after google has done authenticating the user? Thanks

    Reference : https://developers.google.com/identity/protocols/oauth2/web-server#httprest From google identity documentation

    state Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response. The server returns the exact value that you send as a name=value pair in the URL query component (?) of the redirect_uri after the user consents to or denies your application's access request.

    You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery. Since your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request. If you generate a random string or encode the hash of a cookie or another value that captures the client's state, you can validate the response to additionally ensure that the request and response originated in the same browser, providing protection against attacks such as cross-site request forgery. See the OpenID Connect documentation for an example of how to create and confirm a state token.

    Similar issue: https://github.com/googleapis/google-auth-library-ruby/issues/94

    opened by limjinyung 0
  • Username populated by sub in Azure AD OIDC a random number

    Username populated by sub in Azure AD OIDC a random number

    Gitea supports the ability to choose nickname, email, or userid for auto registration. The openidConnect provider hard codes the UserID to the 'sub' claim. In Azure AD, the 'sub' claim is an immutable random ID that has no meaning. Can it be possible to specify the claim to use for a username instead?

    https://github.com/markbates/goth/blob/master/providers/openidConnect/openidConnect.go

    opened by jasonvriends 0
  • Azure AD V1/V2 not able to read groups claims

    Azure AD V1/V2 not able to read groups claims

    1. In the latest Gitea 1.16, when I specify the claim name 'groups' and an Azure AD group ID it doesn't seem to do anything. I am trying to get the 'is admin' populated based on a Group ID.

    2. The userid is the object ID of the user in Azure AD. Can this be the first part of the UPN instead?

    https://github.com/markbates/goth/blob/master/providers/azureadv2/azureadv2.go

    opened by jasonvriends 0
  • microsoftonline: gzip of cookie no longer enough

    microsoftonline: gzip of cookie no longer enough

    I am getting the infamous "securecookie: the value is too long" error when using Microsoft online provider. It seems that the returned data, even after gzip compression, is coming in at around 3,974 bytes and failing to be set.

    We need a new mechanism, perhaps using web storage or splitting the cookie into parts?

    opened by mediumdaver 1
  • how to use goth for gitlab when deploying the application on production

    how to use goth for gitlab when deploying the application on production

    Hi, I am trying the use goth in my production application. The application is configured to use gitlab as oauth provider. When I try to run the application locally, it works fine but when I move the same application to production, it gives me the below error

    oauth2: cannot fetch token: 401 Unauthorized
    Response: {"error":"invalid_client","error_description":"Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method."}
    

    Any idea? The redirect uri which is being getting created is as follows https://oauth.myapplication.com/auth/gitlab/callback

    opened by vinamra28 1
  • Support for Twitter OAuth2 or State Parameter in OAuth

    Support for Twitter OAuth2 or State Parameter in OAuth

    • Is there a possibility we can get support for Twitter OAuth2
    • Currently my use case is to set state parameter and OAuth 1.1 by Twitter does not support that

    If there are any workarounds available in this package - would really appreciate it! PS: I have been using this package on production and thanks a ton to the maintainers!

    opened by prabhuomkar 2
Releases(v1.72.0)
  • v1.72.0(May 9, 2022)

    What's Changed

    • fix(lastfm): fix auth callback param by @jackmerrill in https://github.com/markbates/goth/pull/456

    New Contributors

    • @jackmerrill made their first contribution in https://github.com/markbates/goth/pull/456

    Full Changelog: https://github.com/markbates/goth/compare/v1.71.1...v1.72.0

    Source code(tar.gz)
    Source code(zip)
  • v1.71.1(Apr 13, 2022)

    What's Changed

    • Fix bug with pointer in apple provider by @yaronius in https://github.com/markbates/goth/pull/455

    Full Changelog: https://github.com/markbates/goth/compare/v1.71.0...v1.71.1

    Source code(tar.gz)
    Source code(zip)
  • v1.71.0(Apr 12, 2022)

    What's Changed

    • Test with go 1.18 by @techknowlogick in https://github.com/markbates/goth/pull/454
    • Migrate from v5 Twitch API to Helix by @huntrar in https://github.com/markbates/goth/pull/444
    • Use Bearer token in Slack by @Steve0x2a in https://github.com/markbates/goth/pull/451
    • Add Bitly provider. by @Lambels in https://github.com/markbates/goth/pull/442

    New Contributors

    • @Steve0x2a made their first contribution in https://github.com/markbates/goth/pull/451
    • @Lambels made their first contribution in https://github.com/markbates/goth/pull/442

    Full Changelog: https://github.com/markbates/goth/compare/v1.70.0...v1.71.0

    Source code(tar.gz)
    Source code(zip)
  • v1.70.0(Apr 12, 2022)

    What's Changed

    • TikTok Provider Support by @kylehqcom in https://github.com/markbates/goth/pull/432
    • bitbucket: check the is_primary and is_confirmed properties on the email address by @pjcdawkins in https://github.com/markbates/goth/pull/447
    • update JWX dependency by @yaronius in https://github.com/markbates/goth/pull/453

    New Contributors

    • @kylehqcom made their first contribution in https://github.com/markbates/goth/pull/432

    Full Changelog: https://github.com/markbates/goth/compare/v1.69.0...v1.70.0

    Source code(tar.gz)
    Source code(zip)
  • v1.69.0(Jan 20, 2022)

    What's Changed

    • Set "access_type=offline" to google provider as default by @shiwano in https://github.com/markbates/goth/pull/396
    • Bump VK provider API version to 5.131 by @nikita-vanyasin in https://github.com/markbates/goth/pull/425
    • Add SetAccessType for Google OAuth by @yyewolf in https://github.com/markbates/goth/pull/424
    • Add WeCom provider by @tsl0922 in https://github.com/markbates/goth/pull/418
    • Add IDToken for google provider by @wgjak47 in https://github.com/markbates/goth/pull/417
    • Drop old Go versions, fix errors and fmt issues by @bentranter in https://github.com/markbates/goth/pull/427
    • Add new Go 1.17 build tags by @bentranter in https://github.com/markbates/goth/pull/428
    • Add Zoom provider by @mxaly in https://github.com/markbates/goth/pull/426
    • Update to jwt/v4 by @zeripath in https://github.com/markbates/goth/pull/438

    New Contributors

    • @shiwano made their first contribution in https://github.com/markbates/goth/pull/396
    • @nikita-vanyasin made their first contribution in https://github.com/markbates/goth/pull/425
    • @tsl0922 made their first contribution in https://github.com/markbates/goth/pull/418
    • @wgjak47 made their first contribution in https://github.com/markbates/goth/pull/417
    • @zeripath made their first contribution in https://github.com/markbates/goth/pull/438

    Full Changelog: https://github.com/markbates/goth/compare/v1.68.0...v1.69.0

    Source code(tar.gz)
    Source code(zip)
  • v1.68.0(Jul 24, 2021)

    • #413 - @6543 - switch jwt lib to maintained one
    • #405 - @k-yomo - Make it possible to set bot_prompt query param for line
    • #391 - @subhan-nadeem - Add a Refresh Token function to the OpenID Connect provider that also returns the refreshed OpenID id_token
    Source code(tar.gz)
    Source code(zip)
  • v1.67.1(Jan 29, 2021)

    Overview

    This release attempts to address a long standing issue in the gothic library's CompleteUserAuth method to prevent a session from being removed until one exists. This has been attempted in the past, but was reported to cause other issues, so if you've recently run into an issue that feels related, please revert to the previous release, v1.67.0.

    Contributors

    • #385 - @dexter1918 - Moved deferring of Logout...
    Source code(tar.gz)
    Source code(zip)
  • v1.67.0(Jan 29, 2021)

    Overview

    This release contains the following:

    • A fix to the Apple provider that handles Apple's POST to the callback URL (instead of GET, which is the standard).
    • A fix to the Discord provider to better handle profile photos.
    • Better support for our OpenID provider.
    • Extra data in the Salesforce provider via the raw data field.
    • Support for the login_hint parameter in the Google provider.

    Contributors

    This release wouldn't have been possible without the hard work from the following people. Thanks to everyone who contributed!

    • #356 - @wunderkind2k1 - Minor adjustment in GetState when apple posts callback (instead of get). Fixes #360
    • #395 - @yaronius - Trying to apply changes from #356
    • #393 - @yyewolf - Unexpected behaviour from github
    • #392 - @subhan-nadeem - Include end_session_endpoint in OpenIDConfig when retrieving the OpenID configuration from the OpenID Discovery endpoint
    • #389 - @yyewolf - Properly fixed discord's avatar
    • #383 - @kainosnoema - Add login_hint parameter to Google provider
    • #384 - @chrisguox - Fix discord avatar url error
    • #386 - @subhan-nadeem - Export OpenIDConfig in openIdConnect provider
    • #387 - @mxaly - Support User.rawData in Salesforce provider
    • #388 - @yyewolf - Added support for gifs in discord
    Source code(tar.gz)
    Source code(zip)
  • v1.66.1(Dec 9, 2020)

    • #380 - @unlimitedcoder2 - Move the discord provider to the new discord url
    • #379 - @brittonhayes - Added Okta to list of providers in README.md
    • #361 - @dstapleton92 - Update Apple provider to use %20 space encoding instead of +
    Source code(tar.gz)
    Source code(zip)
  • v1.66.0(Nov 6, 2020)

    • #377 - @JoshKCarroll - Add OuraRing provider
    • #373 - @suntala - Update go version to 1.15
    • #372 - @wahyuoi - Enable test with -race param
    • #371 - @qornanali - Support code formatting
    Source code(tar.gz)
    Source code(zip)
  • v1.65.0(Oct 6, 2020)

  • v1.64.2(Jun 15, 2020)

    • Fixes the Twitch provider to include the Client ID in the header.
    • Fixes the Apple provider when params are form encoded in POST requests.
    Source code(tar.gz)
    Source code(zip)
  • v1.64.1(May 19, 2020)

    • Updates the Heroku provider so that a version along with Heroku’s API MIME type is passed in the Accept header. Thanks @michaeldwan!
    Source code(tar.gz)
    Source code(zip)
  • v1.64.0(Apr 7, 2020)

  • v1.63.0(Mar 28, 2020)

  • v1.62.0(Mar 13, 2020)

  • v1.61.3(Mar 5, 2020)

  • v1.61.2(Feb 24, 2020)

    • Updates the GitHub provider to use the authorization header for authentication. Thanks @mrkschan!
    • Fixes a JWT decoding issue in the OpenID provider. Thanks @oscarlofwenhamn!
    Source code(tar.gz)
    Source code(zip)
  • v1.61.1(Jan 31, 2020)

  • v1.61.0(Jan 16, 2020)

    • Adds the email and is_private_email fields to the Apple provider's GetUser implementation. Thanks @dstapleton92!
    • Modifies gothic to export a non-collidable context key for setting the Provider in a context.Context. Thanks @zinefer!
    Source code(tar.gz)
    Source code(zip)
  • v1.60.0(Dec 19, 2019)

  • v1.59.0(Oct 31, 2019)

  • v1.58.1(Oct 29, 2019)

  • v1.58.0(Oct 22, 2019)

  • v1.57.0(Oct 9, 2019)

  • v1.56.0(Aug 15, 2019)

  • v1.55.0(Aug 12, 2019)

    • Fixes provider deduction from existing sessions so that an argument is not needed on the authentication landing page. Thanks @akramer! πŸŽ‰
    Source code(tar.gz)
    Source code(zip)
  • v1.54.1(Jun 18, 2019)

    • Updates the Salesforce provider to export the AuthURL and TokenURL. This enables consumers of the package to override them, which is necessary to use custom URLs when authenticating with Salesforce Community instances. Thanks @kkirsche! πŸŽ‰
    Source code(tar.gz)
    Source code(zip)
  • v1.54.0(Jun 14, 2019)

  • v1.53.0(May 24, 2019)

Owner
Mark Bates
Mark Bates is a full stack web developer with over 18 years of experience building high quality scalable applications for companies.
Mark Bates
A collection of authentication Go packages related to OIDC, JWKs and Distributed Claims.

cap (collection of authentication packages) provides a collection of related packages which enable support for OIDC, JWT Verification and Distributed Claims.

HashiCorp 327 May 17, 2022
Authorization and authentication. Learning go by writing a simple authentication and authorization service.

Authorization and authentication. Learning go by writing a simple authentication and authorization service.

Dinesh Bhattarai 0 Jan 30, 2022
A simple passwordless authentication middleware that uses only email as the authentication provider

email auth A simple passwordless authentication middleware that uses only email as the authentication provider. Motivation I wanted to restrict access

Miroslav Ε edivΓ½ 4 Jan 31, 2022
Authelia: an open-source authentication and authorization server providing two-factor authentication

Authelia is an open-source authentication and authorization server providing two

Streato 0 Jan 5, 2022
Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication

Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication

Paul Greenberg 372 May 15, 2022
🍍Jeff provides the simplest way to manage web sessions in Go.

jeff A tool for managing login sessions in Go. Motivation I was looking for a simple session management wrapper for Go and from what I could tell ther

Alan Braithwaite 238 May 9, 2022
A reverse proxy that provides authentication with Google, Github or other providers.

A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) to validate accounts by email, domain or group.

OAuth2 Proxy 5.2k May 15, 2022
A reverse proxy that provides authentication with Google, Github or other providers.

A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) to validate accounts by email, domain

OAuth2 Proxy 5.2k May 17, 2022
AuthService is a service that provides authentication with Minecraft Mojang.

AuthService AuthService is a service that provides authentication with Minecraft Mojang. Protobuf is managed by Buf. Command to pull Protobuf files wi

Layercraft 1 Mar 11, 2022
A simple authentication web application in Golang (using jwt)

Simple Authentication WebApp A simple authentication web app in Go (using JWT) Routes Path Method Data /api/v1/auth/register POST {"firstname":,"lastn

Shayan 2 Feb 6, 2022
Package gorilla/securecookie encodes and decodes authenticated and optionally encrypted cookie values for Go web applications.

securecookie securecookie encodes and decodes authenticated and optionally encrypted cookie values. Secure cookies can't be forged, because their valu

Gorilla Web Toolkit 570 May 9, 2022
Authentication service that keeps you in control without forcing you to be an expert in web security.

Authentication service that keeps you in control without forcing you to be an expert in web security.

Keratin 1.1k Apr 30, 2022
Handle Web Authentication for Go apps that wish to implement a passwordless solution for users

WebAuthn Library This library is meant to handle Web Authentication for Go apps that wish to implement a passwordless solution for users. While the sp

Duo Labs 798 May 13, 2022
Handle Web Authentication for Go apps that wish to implement a passwordless solution for users

WebAuthn Library This library is meant to handle Web Authentication for Go apps that wish to implement a passwordless solution for users. While the sp

null 5 Apr 19, 2022
This package provides json web token (jwt) middleware for goLang http servers

jwt-auth jwt auth middleware in goLang. If you're interested in using sessions, checkout my sessions library! README Contents: Quickstart Performance

Adam Hanna 216 May 13, 2022
[DEPRECATED] Go package authcookie implements creation and verification of signed authentication cookies.

Package authcookie import "github.com/dchest/authcookie" Package authcookie implements creation and verification of signed authentication cookies. Co

Dmitry Chestnykh 112 Nov 19, 2021
Herbert Fischer 196 Nov 17, 2021
The mep-agent module provides proxy services for 3rd applications to MEP.

Mep-Agent Introduction Mep-Agent is a middleware that provides proxy services for third-party apps. It can help apps, which do not implement the ETSI

EdgeGallery 21 Mar 9, 2022
Simple authentication and books management with GoFiber

Simple authentication and books management with GoFiber Simple authentication system with gofiber. Endpoints GET /api - Welcome message POST /api/auth

Arif Amir 9 Apr 30, 2022