oauth2

package module
v0.0.0-...-d1c3bb3 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2014 License: Apache-2.0 Imports: 8 Imported by: 0

README

negroni-oauth2 GoDoc wercker status

Allows your Negroni application to support user login via an OAuth 2.0 backend. Requires negroni-sessions middleware.

Google, Facebook, LinkedIn and Github sign-in are currently supported.

Once endpoints are provided, this middleware can work with any OAuth 2.0 backend.

Usage

package main

import (
	"fmt"
	"net/http"

	"github.com/codegangsta/negroni"
	"github.com/goincremental/negroni-oauth2"
	"github.com/goincremental/negroni-sessions"
)

func main() {

	secureMux := http.NewServeMux()

	// Routes that require a logged in user
	// can be protected by using a separate route handler
	// If the user is not authenticated, they will be
	// redirected to the login path.
	secureMux.HandleFunc("/restrict", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		fmt.Fprintf(w, "OK: %s", token.Access())
	})

	secure := negroni.New()
	secure.Use(oauth2.LoginRequired())
	secure.UseHandler(secureMux)

	n := negroni.New()
	n.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	n.Use(oauth2.Google(&oauth2.Options{
		ClientID:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "redirect_url",
		Scopes:       []string{"email"},
	}))

	router := http.NewServeMux()

	//routes added to mux do not require authentication
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		if token == nil || token.IsExpired() {
			fmt.Fprintf(w, "not logged in, or the access token is expired")
			return
		}
		fmt.Fprintf(w, "logged in")
		return
	})

	//There is probably a nicer way to handle this than repeat the restricted routes again
	//of course, you could use something like gorilla/mux and define prefix / regex etc.
	router.Handle("/restrict", secure)

	n.UseHandler(router)

	n.Run(":3000")
}

Auth flow

  • /login will redirect user to the OAuth 2.0 provider's permissions dialog. If there is a next query param provided, user is redirected to the next page afterwards.
  • If user agrees to connect, OAuth 2.0 provider will redirect to /oauth2callback to let your app to make the handshake. You need to register /oauth2callback as a Redirect URL in your application settings.
  • /logout will log the user out. If there is a next query param provided, user is redirected to the next page afterwards.

You can customize the login, logout, oauth2callback and error paths:

oauth2.PathLogin = "/oauth2login"
oauth2.PathLogout = "/oauth2logout"
...

Authors

Derived from martini-contrib/oauth2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Path to handle OAuth 2.0 logins.
	PathLogin = "/login"
	// Path to handle OAuth 2.0 logouts.
	PathLogout = "/logout"
	// Path to handle callback from OAuth 2.0 backend
	// to exchange credentials.
	PathCallback = "/oauth2callback"
	// Path to handle error cases.
	PathError = "/oauth2error"
)

Functions

func Facebook

func Facebook(opt ...oauth2.Option) negroni.Handler

func Github

func Github(opt ...oauth2.Option) negroni.Handler

Github returns a new Github OAuth 2.0 backend endpoint.

func Google

func Google(opt ...oauth2.Option) negroni.Handler

Google returns a new Google OAuth 2.0 backend endpoint.

func LinkedIn

func LinkedIn(opt ...oauth2.Option) negroni.Handler

func LoginRequired

func LoginRequired() negroni.HandlerFunc

Handler that redirects user to the login page if user is not logged in.

func NewOAuth2Provider

func NewOAuth2Provider(opts []oauth2.Option) negroni.HandlerFunc

Returns a generic OAuth 2.0 backend endpoint.

func SetToken

func SetToken(r *http.Request, t interface{})

Types

type Options

type Options struct {
	// ClientID is the OAuth client identifier used when communicating with
	// the configured OAuth provider.
	ClientID string `json:"client_id"`

	// ClientSecret is the OAuth client secret used when communicating with
	// the configured OAuth provider.
	ClientSecret string `json:"client_secret"`

	// RedirectURL is the URL to which the user will be returned after
	// granting (or denying) access.
	RedirectURL string `json:"redirect_url"`

	// Optional, identifies the level of access being requested.
	Scopes []string `json:"scopes"`

	// Optional, "online" (default) or "offline", no refresh token if "online"
	AccessType string `json:"omit"`

	// ApprovalPrompt indicates whether the user should be
	// re-prompted for consent. If set to "auto" (default) the
	// user will be prompted only if they haven't previously
	// granted consent and the code can only be exchanged for an
	// access token.
	// If set to "force" the user will always be prompted, and the
	// code can be exchanged for a refresh token.
	ApprovalPrompt string `json:"omit"`
}

type Tokens

type Tokens interface {
	Access() string
	Refresh() string
	Expired() bool
	ExpiryTime() time.Time
}

Represents a container that contains user's OAuth 2.0 access and refresh tokens.

func GetToken

func GetToken(r *http.Request) Tokens

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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