oauthmw

package module
v0.0.0-...-46bb80d Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2016 License: MIT Imports: 16 Imported by: 0

README

About oauthmw Build Status Coverage Status

A Goji v2 middleware package for handling OAuth2.0 login flows.

Installation

Install the package via the following:

go get -u github.com/knq/oauthmw

Usage

Please see the GoDoc API page for a full API listing.

The oauthmw package can be used similarly to the following:

// example/example.go
package main

import (
    "fmt"
    "net/http"
    "os"

    "golang.org/x/net/context"

    "goji.io"
    "goji.io/pat"

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

    "github.com/knq/oauthmw"
    "github.com/knq/sessionmw"
)

func main() {
    // create session
    sess := &sessionmw.Config{
        Name:        "mySessionCookie",
        Secret:      []byte("K7qv0EG3tBvDXCXhPcrRmdceS0RCMm8B"),
        BlockSecret: []byte("xUYUQ4seHVFFhJ2iInWpnfPHrYomVeaf"),
        Store:       sessionmw.NewMemStore(),
    }

    // create oauthmw provider
    prov := oauthmw.Provider{
        Secret:      []byte("NzfWi6Sj3gQ8cEUmu3f705bGLyGJ6Xh3"),
        BlockSecret: []byte("LxUpc1GPFKFQ5tMpciQAgv5o80yuzBzH"),
        Path:        "/",
        Configs: map[string]*oauth2.Config{
            "google": {
                Endpoint:     google.Endpoint,
                ClientID:     os.Getenv("OAUTHMW_GOOGLEID"),
                ClientSecret: os.Getenv("OAUTHMW_GOOGLESECRET"),
                RedirectURL:  "http://localhost:8000/oauth-login",
                Scopes: []string{
                    "https://www.googleapis.com/auth/plus.login",
                    "https://www.googleapis.com/auth/userinfo.email",
                },
            },
            "facebook": {
                Endpoint:     facebook.Endpoint,
                ClientID:     os.Getenv("OAUTHMW_FACEBOOKID"),
                ClientSecret: os.Getenv("OAUTHMW_FACEBOOKSECRET"),
                RedirectURL:  "http://localhost:8000/oauth-login",
                Scopes: []string{
                    "public_profile,email",
                },
            },
        },
    }

    mux := goji.NewMux()

    // add middleware
    mux.UseC(sess.Handler)
    mux.UseC(prov.RequireLogin(func(provName string, config *oauth2.Config, token *oauth2.Token) (string, bool) {
        // this is a super fancy check callback function
        switch provName {
        case "facebook":
            // client := config.Client(context, token)
        case "google":
            // client := config.Client(context, token)

        default:
            return "bad provider!", false
        }

        // no errors encountered
        return "", true
    }))

    // simple demonstration handler
    mux.HandleFuncC(pat.Get("/*"), func(ctxt context.Context, res http.ResponseWriter, req *http.Request) {
        http.Error(res, fmt.Sprintf("this is my protected area! path: %+v", ctxt), http.StatusOK)
    })

    // serve
    http.ListenAndServe(":8000", mux)
}

Documentation

Overview

Package oauthmw provides an OAuth2.0 login flow middleware for Goji v2.

Index

Constants

View Source
const (
	// DefaultSessionKey is the default key used for the oauthmw session store.
	//
	// Override with Provider.SessionKey
	DefaultSessionKey = "oauthmw"

	// DefaultPagePrefix is the default page prefix used for oauthmw pages.
	//
	// Override with Provider.PagePrefix
	DefaultPagePrefix = "oauth-"

	// DefaultRedirectPrefix is the default prefix used for redirects to
	// OAuth2.0 pages.
	//
	// Override with Provider.
	DefaultRedirectPrefix = "redirect-"

	// DefaultReturnName is the default path name used for return (login).
	//
	// Override with Provider.ReturnName
	DefaultReturnName = "login"

	// DefaultLogoutName is the default path name used for logout.
	//
	// Please note this is not yet implemented.
	//
	// Override with Provider.LogoutName
	DefaultLogoutName = "logout"

	// DefaultStateLifetime is the default lifetime (ttl) for an oauth2
	// transfer state.
	//
	// Override with Provider.StateLifetime
	DefaultStateLifetime = 12 * time.Hour

	// DefaultMaxStates is the maximum number of states allowed in the session
	// storage before a cleanup is triggered.
	//
	// Override with Provider.MaxStates
	DefaultMaxStates = 128
)
View Source
const DefaultProtectedPageTpl = `` /* 256-byte string literal not displayed */

DefaultProtectedPageTpl is the default protected page template.

Variables

This section is empty.

Functions

This section is empty.

Types

type CheckFn

type CheckFn func(string, *oauth2.Config, *oauth2.Token) (string, bool)

A CheckFn is passed a provider name, the original provider config, and the redeemed token after a successful OAuth2.0 exchange.

CheckFn should return a redirect URL (if any) and whether or not to allow the login.

type Provider

type Provider struct {
	// Secret for oauth2 transfer state (passed to gorilla/securecookie).
	//
	// Must not be empty.
	Secret []byte

	// BlockSecret for oauth2 transfer state (passed to gorilla/securecookie).
	//
	// Must not be empty.
	BlockSecret []byte

	// Path that is being secured.
	//
	// Used for redirects. Must not be empty.
	Path string

	// Configs for oauth2
	Configs map[string]*oauth2.Config

	// SessionKey is the key used to retrieve the oauthmw states from the
	// session.
	//
	// Should be unique per path.
	//
	// If empty, then this is set as the DefaultSessionKey plus the first 6
	// characters of the md5 hash of the Provider.Path.
	SessionKey string

	// StateLifetime is the lifetime (ttl) of an oauth2 transfer state.
	StateLifetime time.Duration

	// TokenLifetime is maximum allowed token lifetime (ttl) after redemption.
	//
	// This is useful if you want to force an expiration for redeemed oauth2
	// tokens.
	TokenLifetime time.Duration

	// PagePrefix is the prefix used to check all page requests (default: "oauth-")
	//
	// All redirect/return/logout paths must start with this prefix.
	PagePrefix string

	// RedirectPrefix is the optional path prefix used for redirects (default: "redirect-").
	RedirectPrefix string

	// ReturnName is the path name used for returns (default: "login").
	ReturnName string

	// LogoutName is the path name used for logout (default: "logout").
	//
	// Please note that logout is not yet implemented.
	LogoutName string

	// ConfigsOrder is an optional for the configs processing on the protected
	// page template.
	//
	// Optional to specify, but when provided then this is the order that
	// providers are listed in the template to users.
	ConfigsOrder []string // FIXME -- not implemented properly

	// TemplateFn is the function used for generating template on protected
	// page when there is no valid oauth2.Token in the session.
	TemplateFn func(http.ResponseWriter, *http.Request, map[string]interface{})

	// ErrorFn is the function called when an error is produced.
	ErrorFn func(int, string, http.ResponseWriter, *http.Request)

	// CleanupStates when true causes simple cleanup to happen on the oauth2
	// transfer states stored in the session that are already expired.
	CleanupStates bool

	// MaxStates is the number of states allowed before cleanup is triggered.
	//
	// Set to -1 for unlimited states.
	MaxStates int
}

Provider configuration.

func (Provider) DecodeState

func (p Provider) DecodeState(data string) (map[string]string, error)

DecodeState decodes the oauth2 transfer state encoded with EncodeState.

func (Provider) EncodeState

func (p Provider) EncodeState(sessionID, provName, resource string) (string, error)

EncodeState returns an encoded (and secure) oauth2 transfer state for the provided session id, named provider, and specified resource.

func (Provider) Login

func (p Provider) Login(checkFn CheckFn) func(goji.Handler) goji.Handler

Login provides a goji.Handler that handles oauth2 login flows, but does not require there to be a login.

NOTE: Any mux using this middleware WILL be visible to an unauthenticated user.

func (Provider) RequireLogin

func (p Provider) RequireLogin(checkFn CheckFn) func(goji.Handler) goji.Handler

RequireLogin provides goji.Handler that handles oauth2 login flows, requiring that there be a valid login prior to acessing a protected resource.

type Store

type Store struct {
	// Provider name of token.
	Provider string `json:"provider"`

	// Token is redeemed oauth2 token.
	Token *oauth2.Token `json:"token,omitempty"`

	// States are the passed states sent to oauth2 providers.
	States map[string]StoreState `json:"states"`
}

Store is the object used by oauthmw in the session.

type StoreState

type StoreState struct {
	// Provider name of state.
	Provider string `json:"provider"`

	// Expiration is when the state expires.
	Expiration time.Time `json:"expiration"`

	// Redeemed indicates whether or not the state has been previously redeemed.
	Redeemed bool `json:"redeemed"`
}

StoreState is storage for a passed oauth2 in a session.

Directories

Path Synopsis
example/example.go
example/example.go

Jump to

Keyboard shortcuts

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