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

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
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
Comments
  • 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

  • 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

  • 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.

  • 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

  • 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

  • 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).

  • 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?

  • 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 ?

  • 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

  • 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.

  • 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

  • mailru error

    mailru error

    response from mailru - "The application ID was not passed in the client_id parameter"

    goth/providers/mailru/mailru.go: const ( authURL = "https://connect.mail.ru/oauth/authorize" )

    but in https://o2.mail.ru/docs#web mail ru write that endpoint is "https://oauth.mail.ru/login"

    also changed token endpoint to "https://oauth.mail.ru/token"

    I'll try to check it out. I'll write the result later.

  • Add cognito provider

    Add cognito provider

    Added support for AWS Cognito. New takes 3 parameters all from the Cognito console:

    • The client ID
    • The client secret
    • The base URL for your servcice, either a custom domain or cognito pool based URL You need to ensure that the source login URL is whitelisted as a login page in the client configuration in the cognito console. GOTH does not provide a full token logout, to do that you need to do it in your code, my recommendation is a) Destroy your session (or however else you handle the logout internally) b) redirect to https://customdomain.auth.us-east-1.amazoncognito.com/logout?client_id=clinet_id&logout_uri=http://localhost:8080/ (or whatever your login/start page is). c) Note that this page needs to be whitelabeled as a logout page in the cognito console as well.

    This has been tested using goth_fiber.

  • Attempted fix for #483 - Use Activitypub FQN as email during sign up.

    Attempted fix for #483 - Use Activitypub FQN as email during sign up.

    I have attempted to use the strategies from the discord oauth (which has email handing) for mastodon, to provide the oauth client a usable email in the form of the user fqn ([email protected]) which should allow gitea to create user accounts through oauth, please correct if needed, but I think this might work.

    Linked to issues #483 and go-gitea/gitea#21710

  • feat/azureadv2: retrieve ID token from response if available

    feat/azureadv2: retrieve ID token from response if available

    Currently the Azure AD v2 provider gets back the access token and ID token in its response when exchanging the authorization code, but it ignores the ID token. This PR retrieves the ID token from the response and passes it back through to the API consumer via the return User.

  • has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    Hi Master,

    I faced a cors issue, investigate a lot but didn't find any solution, anyone can help?

    • Backend Web Framework: Gin
    • Provider: Google
    • API: Get /auth?provider=google Get /auth/google/callback
    • Frontend: react axios.get('/auth', { params: { provider: "google", } })

    Error Message: Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=xxxx&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fgoogle%2Fcallback&response_type=code&scope=email+profile&state=xxxx' (redirected from 'http://localhost:3000/auth?provider=google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

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.

Aug 5, 2022
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.

Dec 7, 2022
A simple passwordless authentication middleware that uses only email as the authentication provider
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

Jul 27, 2022
Authelia: an open-source authentication and authorization server providing two-factor authentication
Authelia: an open-source authentication and authorization server providing two-factor authentication

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

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

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

Jan 8, 2023
🍍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

Jan 4, 2023
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

Dec 26, 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

Feb 6, 2022
A reverse proxy that provides authentication with Google, Github or other providers.
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.

Jan 8, 2023
A reverse proxy that provides authentication with Google, Github or other providers.
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

Jan 1, 2023
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

Aug 20, 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

Dec 5, 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

Dec 22, 2022
Oct 8, 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.

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

Jan 1, 2023
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

Dec 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

Jan 1, 2023
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

Mar 9, 2022
Certificate authority and access plane for SSH, Kubernetes, web applications, and databases

Teleport is an identity-aware, multi-protocol access proxy which understands SSH, HTTPS, Kubernetes API, MySQL and PostgreSQL wire protocols.

Jan 9, 2023