google_oauth_handler

package module
v0.0.0-...-602fca6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2019 License: MIT Imports: 18 Imported by: 0

README

google-oauth-handler

Package google_oauth_handler transparently handles OAuth authentication with Google.

Create an Authenticator and then insert it as middleware in front of any resources you want to protect behind Google login, via authenticator.Handle. Handle will call the next middleware with (w, r, *Auth), which you can use to make requests to the Google API.

The Authenticator handles the OAuth workflow for you, redirecting users to Google, handling the callback and setting an encrypted cookie in the user's browser.

For more information, see the godoc documentation.

Example
package google_oauth_handler_test

import (
	"encoding/hex"
	"fmt"
	"net/http"

	google "github.com/kevinburke/google-oauth-handler"
	"golang.org/x/oauth2"
)

var key *[32]byte

func init() {
	secretKeyBytes, _ := hex.DecodeString("982a732cc3d72d13678dee2609cf55d736711ff1f293f95cab41bd45e5d77870")
	key = new([32]byte)
	copy(key[:], secretKeyBytes)
}

func Example() {
	cfg := google.Config{
		SecretKey: key,
		BaseURL:   "https://example.com",
		ClientID:  "customdomain.apps.googleusercontent.com",
		Secret:    "W-secretkey",
		Scopes: []string{
			"email",
			"https://www.googleapis.com/auth/gmail.send",
		},
	}
	auth := google.NewAuthenticator(cfg)
	http.Handle("/", auth.Handle(func(w http.ResponseWriter, r *http.Request, auth *google.Auth) {
		fmt.Fprintf(w, "<html><body><h1>Hello World</h1><p>Token: %s</p></body></html>", auth.AccessToken)
	}))
}

Documentation

Overview

Package google_oauth_handler transparently handles OAuth authentication with Google.

Create an Authenticator and then insert it as middleware in front of any resources you want to protect behind Google login, via authenticator.Handle. Handle will call the next middleware with (w, r, *Token), which you can use to make requests to the Google API.

The Authenticator handles the OAuth workflow for you, redirecting users to Google, handling the callback and setting an encrypted cookie in the user's browser.

Example
package main

import (
	"encoding/hex"
	"fmt"
	"net/http"

	google "github.com/kevinburke/google-oauth-handler"
)

var key *[32]byte

func init() {
	secretKeyBytes, _ := hex.DecodeString("982a732cc3d72d13678dee2609cf55d736711ff1f293f95cab41bd45e5d77870")
	key = new([32]byte)
	copy(key[:], secretKeyBytes)
}

func main() {
	cfg := google.Config{
		SecretKey: key,
		BaseURL:   "https://example.com",
		ClientID:  "customdomain.apps.googleusercontent.com",
		Secret:    "W-secretkey",
		Scopes: []string{
			"email",
			"https://www.googleapis.com/auth/gmail.send",
		},
	}
	authenticator := google.NewAuthenticator(cfg)
	http.Handle("/", authenticator.Handle(func(w http.ResponseWriter, r *http.Request, auth *google.Auth) {
		fmt.Fprintf(w, "<html><body><h1>Hello World</h1><p>Token: %s</p></body></html>", auth.Token.AccessToken)
	}))
}
Output:

Index

Examples

Constants

View Source
const Version = "0.5"

Variables

View Source
var AuthTimeout = 1 * time.Hour

AuthTimeout is the amount of time to allow users to complete an authentication attempt.

View Source
var DefaultExpiry = 14 * 24 * time.Hour

DefaultExpiry is the duration of a valid cookie.

View Source
var Timeout = 30 * time.Second

Timeout is the amount of time to wait for a response from Google when asking for information.

Functions

This section is empty.

Types

type Auth

type Auth struct {
	// The Google email address for this user.
	Email *mail.Address
	// A Client that's configured to use the Google credentials
	Client *http.Client
	Token  *oauth2.Token
}

Auth is returned in the callback to Handle().

type Authenticator

type Authenticator struct {
	// contains filtered or unexported fields
}

An Authenticator transparently handles authentication with Google. Create an Authenticator by calling NewAuthenticator(Config{}).

func NewAuthenticator

func NewAuthenticator(c Config) *Authenticator

NewAuthenticator creates a new Authenticator that can authenticate requests via Google login.

To get a clientID and clientSecret, see https://github.com/saintpete/logrole/blob/master/docs/google.md.

func (*Authenticator) Handle

func (a *Authenticator) Handle(f func(http.ResponseWriter, *http.Request, *Auth)) http.Handler

Handle returns an http.Handler that only calls f if the request carries a valid authentication cookie. If not, a.Login is called, to trigger an authentication workflow with Google. If the user approves access for the provided scopes, we set an encrypted cookie on the request and call f(w, r, token). The token can then be used to make requests to Google's APIs.

Handle must handle requests to the CallbackPath (which defaults to /auth/callback) in order to set a valid cookie.

func (*Authenticator) Logout

func (a *Authenticator) Logout(w http.ResponseWriter)

Logout wipes the Google authentication cookie from w.

func (*Authenticator) SetLogin

func (a *Authenticator) SetLogin(h http.Handler)

SetLogin sets the login handler to h. A convenience handler since this may be configured later than the other parts of the google oauth handler's config.

func (*Authenticator) URL

func (a *Authenticator) URL(r *http.Request) string

URL returns a link to the Google auth URL for this Authenticator. If the http.Request contains a query parameter named "g", the user will be redirected to that page upon returning from Google.

Example
cfg := google.Config{
	SecretKey: key,
	BaseURL:   "https://example.com",
	ClientID:  "customdomain.apps.googleusercontent.com",
	Secret:    "W-secretkey",
	Scopes: []string{
		"email",
		"https://www.googleapis.com/auth/gmail.send",
	},
}
auth := google.NewAuthenticator(cfg)
r, _ := http.NewRequest("GET", "/", nil)
fmt.Println(auth.URL(r)) // "https://accounts.google.com/o/oauth2/..."
Output:

type Config

type Config struct {
	// The logger to use for logging errors in the authentication workflow.
	Logger log.Logger
	// BaseURL is the server's base URL (scheme+host), used to set cookies.
	BaseURL string
	// SecretKey is used to encrypt and decrypt the OAuth nonce and cookies.
	SecretKey *[32]byte

	// The Google ClientID and Secret. To figure out how to get these, visit
	// https://github.com/saintpete/logrole/blob/master/docs/google.md
	ClientID string
	Secret   string

	// List of scopes (a.k.a permissions) to ask for.
	// For a list of valid scopes see https://developers.google.com/identity/protocols/googlescopes.
	Scopes []string
	// Set to "false" to set Secure: false on cookies.
	AllowUnencryptedTraffic bool
	// If non-empty, limit access to users with email addresses in these domains.
	AllowedDomains []string
	// ServeLogin will be called when the user needs to authenticate with
	// Google, for example if you want to display a custom login page with
	// a "Log in with Google" button.
	//
	// If ServeLogin is nil, all users that need to authenticate will be
	// immediately redirected to Google.
	ServeLogin http.Handler
	// Which URL Google should hit when they redirect users back to your site
	// after logging in. Defaults to "/auth/callback".
	CallbackPath string
}

Config allows users to configure an Authenticator.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL