Go login handlers for authentication providers (OAuth1, OAuth2)

Related tags

gologin
Overview

gologin Build Status GoDoc

Package gologin provides chainable login http.Handler's for Google, Github, Twitter, Facebook, Bitbucket, Tumblr, or any OAuth1 or OAuth2 authentication providers.

Choose a subpackage. Register the LoginHandler and CallbackHandler for web logins or the TokenHandler for (mobile) token logins. Get the authenticated user or access token from the request context.

See examples for tutorials with apps you can run from the command line.

Features

  • LoginHandler and CallbackHandler support web login flows
  • TokenHandler supports native mobile token login flows
  • Obtain the user or access token from the context
  • Configurable OAuth 2 state parameter handling (CSRF protection)
  • Configurable OAuth 1 request secret handling

Install

go get github.com/dghubble/gologin

Docs

Read GoDoc or check the examples.

Overview

Package gologin provides http.Handler's which can be chained together to implement authorization flows by passing data (e.g. tokens, users) via the request context. gologin handlers take success and failure next http.Handler's to be called when authentication succeeds or fails. Chaining allows advanced customization, if desired. Once authentication succeeds, your success handler will have access to the user's access token and associated User/Account.

Usage

Choose a subpackage such as github or twitter. LoginHandler and Callback http.Handler's chain together lower level oauth1 or oauth2 handlers to authenticate users and fetch the Github or Twitter User, before calling your success http.Handler.

Let's walk through Github and Twitter web login examples.

Github OAuth2

Register the LoginHandler and CallbackHandler on your http.ServeMux.

config := &oauth2.Config{
    ClientID:     "GithubClientID",
    ClientSecret: "GithubClientSecret",
    RedirectURL:  "http://localhost:8080/callback",
    Endpoint:     githubOAuth2.Endpoint,
}
mux := http.NewServeMux()
stateConfig := gologin.DebugOnlyCookieConfig
mux.Handle("/login", github.StateHandler(stateConfig, github.LoginHandler(config, nil)))
mux.Handle("/callback", github.StateHandler(stateConfig, github.CallbackHandler(config, issueSession(), nil)))

The StateHandler checks for an OAuth2 state parameter cookie, generates a non-guessable state as a short-lived cookie if missing, and passes the state value in the ctx. The CookieConfig allows the cookie name or expiration (default 60 seconds) to be configured. In production, use a config like gologin.DefaultCookieConfig which sets Secure true to require cookies be sent over HTTPS. If you wish to persist state parameters a different way, you may chain your own http.Handler. (info)

The github LoginHandler reads the state from the ctx and redirects to the AuthURL (at github.com) to prompt the user to grant access. Passing nil for the failure handler just means the DefaultFailureHandler should be used, which reports errors. (info)

The github CallbackHandler receives an auth code and state OAuth2 redirection, validates the state against the state in the ctx, and exchanges the auth code for an OAuth2 Token. The github CallbackHandler wraps the lower level oauth2 CallbackHandler to further use the Token to obtain the Github User before calling through to the success or failure handlers.

Next, write the success http.Handler to do something with the Token and Github User added to the ctx.

func issueSession() http.Handler {
    fn := func(w http.ResponseWriter, req *http.Request) {
        ctx := req.Context()
        token, _ := oauth2Login.TokenFromContext(ctx)
        githubUser, err := github.UserFromContext(ctx)
        // handle errors and grant the visitor a session (cookie, token, etc.)
    }
    return http.HandlerFunc(fn)
}

See the Github tutorial for a web app you can run from the command line.

Twitter OAuth1

Register the LoginHandler and CallbackHandler on your http.ServeMux.

config := &oauth1.Config{
    ConsumerKey:    "TwitterConsumerKey",
    ConsumerSecret: "TwitterConsumerSecret",
    CallbackURL:    "http://localhost:8080/callback",
    Endpoint:       twitterOAuth1.AuthorizeEndpoint,
}
mux := http.NewServeMux()
mux.Handle("/login", twitter.LoginHandler(config, nil))
mux.Handle("/callback", twitter.CallbackHandler(config, issueSession(), nil))

The twitter LoginHandler obtains a request token and secret, adds them to the ctx, and redirects to the AuthorizeURL to prompt the user to grant access. Passing nil for the failure handler just means the DefaultFailureHandler should be used, which reports errors. (info)

The twitter CallbackHandler receives an OAuth1 token and verifier, reads the request secret from the ctx, and obtains an OAuth1 access token and secret. The twitter CallbackHandler wraps the lower level oauth1 CallbackHandler to further use the access token/secret to obtain the Twitter User before calling through to the success or failure handlers.

Next, write the success http.Handler to do something with the access token/secret and Twitter User added to the ctx.

func success() http.Handler {
    fn := func(w http.ResponseWriter, req *http.Request) {
        ctx := req.Context()
        accessToken, accessSecret, _ := oauth1Login.AccessTokenFromContext(ctx)
        twitterUser, err := twitter.UserFromContext(ctx)
        // handle errors and grant the visitor a session (cookie, token, etc.)
    }
    return http.HandlerFunc(fn)
}

*Note: Some OAuth1 providers (not Twitter), require the request secret be persisted until the callback is received. For this reason, the lower level oauth1 package splits LoginHandler functionality into a LoginHandler and AuthRedirectHandler. Provider packages, like tumblr, chain these together for you, but the lower level handlers are there if needed.

See the Twitter tutorial for a web app you can run from the command line.

State Parameters

OAuth2 StateHandler implements OAuth 2 RFC 6749 10.12 CSRF Protection using non-guessable values in short-lived HTTPS-only cookies to provide reasonable assurance the user in the login phase and callback phase are the same. If you wish to implement this differently, write a http.Handler which sets a state in the ctx, which is expected by LoginHandler and CallbackHandler.

You may use oauth2.WithState(context.Context, state string) for this. docs

Failure Handlers

If you wish to define your own failure http.Handler, you can get the error from the ctx using gologin.ErrorFromContext(ctx).

Mobile

Twitter includes a TokenHandler which can be useful for building APIs for mobile devices which use Login with Twitter.

Goals

Create small, chainable handlers to correctly implement the steps of common authentication flows. Handle provider-specific validation requirements.

Motivations

Package gologin implements authorization flow steps with chained handlers.

  • Authentication should be performed with chainable handlers to allow customization, swapping, or adding additional steps easily.
  • Authentication should be orthogonal to the session system. Let users choose their session/token library.
  • OAuth2 State CSRF should be included out of the box, but easy to customize.
  • Packages should import only what is required. OAuth1 and OAuth2 packages are separate.
  • http.Handler and context are powerful, flexible, and in the standard library.

Projects goth and gomniauth aim to provide a similar login solution with a different design. Check them out if you decide you don't like the ideas in gologin.

Contributing

New auth providers can be implemented by composing the handlers in the oauth1 or oauth2 subpackages. See the Contributing Guide.

License

MIT License

Issues
  • Update Google API version

    Update Google API version

    The Google API module renamed Userinfoplus to Userinfo; this can lead to incompatibilties when using gologin with other Google API packages.

    This commit updates the dependency version for the Google API wrapper and replaces references to Userinfoplus with simply Userinfo.

    opened by nyergler 7
  • Use Standard library context in Go 1.7

    Use Standard library context in Go 1.7

    I wanted to build on top this library. But first I wanted to use the new context pkg in GO 1.7. I figured I will send a pr, in case you are interested to merge it.

    opened by tamalsaha 6
  • 
Fix function comments based on best practices from Effective Go

    Fix function comments based on best practices from Effective Go

    Every exported function in a program should have a doc comment. The first sentence should be a summary that starts with the name being declared. From effective go.

    PR generated by CodeLingo. Install here to drive Continuous Higher Standards.

    opened by CodeLingoBot 4
  • github: support enterprise instances

    github: support enterprise instances

    Thanks for making a wonderful library!

    This PR adds support for GitHub Enterprise instances. It looks at the AuthURL endpoint to infer whether the GitHub instance is github.com or an enterprise instance.

    opened by beyang 4
  • Use base64.URLEncoding instead of base64.StdEncoding for state parameter

    Use base64.URLEncoding instead of base64.StdEncoding for state parameter

    standard base64 encoding may contain a space characters and there are some situations when session has state with '+' characters but request comes in with ' ' instead of '+'

    opened by adone 3
  • Use base64.RawURLEncoding for StateHandler's state param

    Use base64.RawURLEncoding for StateHandler's state param

    • Avoid using '+' in the state param. A random state value may contain it and some OAuth 2 providers do not correctly URL encode their callback URLs. As a result, the parsed and checked state doesn't match.
    • See #12
    opened by dghubble 2
  • Add support for Apple sign in

    Add support for Apple sign in

    Here's an attempt to add support for Apple sign in, along with a working example and tests.

    Test coverage could be improved, which I am happy to do should there be interest in pulling this in.

    opened by bmilekic 2
  • v2.0.0, Go 1.7+, and standard context support

    v2.0.0, Go 1.7+, and standard context support

    If you're using Go 1.7+ and the new context, you may wish to start using this release candidate.

    # glide.yaml
    - package: github.com/dghubble/gologin
      version: v2.0.0-rc1
    

    Go 1.8 is nearly finalized and Fedora/Debian users should have Go 1.7 by default too. Its probably close to transition time unless there are objections. Aiming to merge when 1.8 release candidate goes out. Go 1.6 support will be dropped in v2.0.0 and continue for a short while as v1.0.* releases.

    Special thanks to @TamalSaha for his commits.

    opened by dghubble 1
  • Add a section about retrieving access token in GitHub example

    Add a section about retrieving access token in GitHub example

    There is no explanation about how to retrieve the user's access token after authentication succeeds. Add a short code fragment to the README for retrieving the token.

    opened by teabolt 1
  • Fix typo in Twitter example README

    Fix typo in Twitter example README

    The directory in the Twitter example points to github instead of twitter.

    opened by jouir 1
Releases(v2.3.0)
  • v2.3.0(Mar 7, 2021)

  • v2.2.0(Aug 9, 2019)

    • Suffix packages with /v2 to provide Go module support (#37)
      • Module users may import github.com/dghubble/gologin/v2 starting in v2.2.0
      • Non-module users may continue using releases prior to v2.2.0
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Nov 20, 2018)

    • Add EnterpriseCallbackHandler for Github Enterprise (#33)
    • Add email address to Facebook Users (0acc88)
    • Update Facebook API version to v2.9 (0acc88)
    • Fix facebook CallbackHandler to pass Facebook errors (#31)
    • Fix Github Users.Get call to accomodate a go-github change (#18)
    • Remove deprecated digits subpackage (#29)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jan 10, 2017)

    • Support for Go 1.7+ standard context
    • Change gologin handlers to be standard http.Handler's
    • Drop requirement for ctxh.NewHandler wrapper
    • Drop dependency on github.com/dghubble/ctxh shim

    Migration

    • Update golang.org/x/net/context imports to context
    • Change any ctxh.ContextHandler to a http.Handler. The ctx is passed via the request so the argument is no longer needed.
    • Remove any ctxh.NewHandler(...) wrap. gologin handlers are now standard http.Handler's, conversion is no longer required.
    • Use req.Context() to obtain the request context within handlers.
    • See updated examples
    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Jan 8, 2017)

    • Use base64.RawURLEncoding for StateHandler's state (#14)
    • Fix OAuth1 failure handler's error passing (#13)
    • Improve test automation. Validate with Go 1.6 and 1.7.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Jan 8, 2017)

    • Official release using the ContextHandler
    • Support for all OAuth1 and Oauth2 providers
    • Convenience handlers for Google, Github, Facebook, Bitbucket, Twitter, Digits, and Tumblr
    • Token login handlers for Twitter and Digits
    Source code(tar.gz)
    Source code(zip)
Owner
Dalton Hubble
Friends with the machines | Kubernetes | @poseidon Typhoon and Matchbox | Previously @lyft, @coreos, @twitter, MIT
Dalton Hubble
Go login handlers for authentication providers (OAuth1, OAuth2)

gologin Package gologin provides chainable login http.Handler's for Google, Github, Twitter, Facebook, Bitbucket, Tumblr, or any OAuth1 or OAuth2 auth

Dalton Hubble 1.4k Jul 23, 2021
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 3.8k Jul 23, 2021
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 3.9k Jul 30, 2021
A standalone, specification-compliant, OAuth2 server written in Golang.

Go OAuth2 Server This service implements OAuth 2.0 specification. Excerpts from the specification are included in this README file to describe differe

Richard Knop 1.8k Jul 23, 2021
JWT login microservice with plugable backends such as OAuth2, Google, Github, htpasswd, osiam, ..

loginsrv loginsrv is a standalone minimalistic login server providing a JWT login for multiple login backends. ** Attention: Update to v1.3.0 for Goog

tarent 1.8k Jul 23, 2021
an SSO and OAuth / OIDC login solution for Nginx using the auth_request module

Vouch Proxy An SSO solution for Nginx using the auth_request module. Vouch Proxy can protect all of your websites at once. Vouch Proxy supports many O

Vouch 1.4k Jul 31, 2021
Go OAuth2

OAuth2 for Go oauth2 package contains a client implementation for OAuth 2.0 spec. Installation go get golang.org/x/oauth2 Or you can manually git clo

Go 3.7k Jul 21, 2021
OAuth 1.0 implementation in go (golang).

OAuth 1.0 Library for Go (If you need an OAuth 2.0 library, check out: https://godoc.org/golang.org/x/oauth2) Developing your own apps, with this libr

Matt Jones 257 Jul 4, 2021
:closed_lock_with_key: Middleware for keeping track of users, login states and permissions

Permissions2 Middleware for keeping track of users, login states and permissions. Online API Documentation godoc.org Features and limitations Uses sec

Alexander F. Rødseth 432 Jul 9, 2021
[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 Jul 10, 2021
A Sample Integration of Google and GitHub OAuth2 in Golang (GoFiber) utilising MongoDB

Go Oauth Server This is sample OAuth integration written in GoLang that also uses MongoDB. This is a sample TODO Application where people can Create a

Hemanth Krishna 3 Jul 7, 2021
Golang OAuth2 server library

OSIN Golang OAuth2 server library OSIN is an OAuth2 server library for the Go language, as specified at http://tools.ietf.org/html/rfc6749 and http://

OpenShift 1.7k Jul 23, 2021
Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applications.

Goth: Multi-Provider Authentication for Go Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applic

Mark Bates 3.3k Jul 30, 2021
🍍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 229 Jul 14, 2021