auth

package module
v0.0.0-...-3b5a6e6 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2012 License: MIT Imports: 10 Imported by: 0

README

go.auth

an http authentication API for the Go programming language. Integrates with 3rd party auth providers to add security to your web application.

go get github.com/dchest/authcookie
go get github.com/bradrydzewski/go.auth

Python's Tornado framework, specifically their auth module, was the main inspiration for this library.

Providers

The following auth providers are supported:

  • Github OAuth 2.0 demo
  • Google OAuth 2.0 demo
  • Google OpenId 2.0 demo
  • Twitter OAuth 1.0a demo

We plan to add support for the following providers:

  • Facebook
  • LinkedIn

Sample Code

Example program using the Google OpenId auth provider:

// Set the default authentication configuration parameters
auth.Config.CookieSecret         = []byte("asdfasdfasfasdfasdfafsd")
auth.Config.LoginRedirect        = "/auth/login"
auth.Config.LoginSuccessRedirect = "/private"

// Create your login handler
githubHandler := auth.NewGithubHandler(githubAccessKey, githubSecretKey)
http.Handle("/auth/login", githubHandler)

// Example of a public http handler
http.HandleFunc("/public", Public)

// Example of a secured http handler
http.HandleFunc("/private", auth.SecureFunc(Private))

You can even mix and match. See the multi-provider demo application.

User data

The user data is passed to your Handler via the URL's User field:

func Foo(w http.ResponseWriter, r *http.Request) {
	user := r.URL.User.Username()
}

Configuration

go.auth uses the following default parameters which can be configured:

Variable Description Default Value
auth.Config.CookieName name of the secure cookie "UID"
auth.Config.CookieSecret key used to encrypt the cookie value nil
auth.Config.CookieExp amount of time before cookie expires time.Hour * 24 * 14
auth.Config.LoginRedirect where to re-direct a user that is not authenticated "/auth/login"
auth.Config.LoginSuccessRedirect where to re-direct a user once authenticated "/"

Example:

auth.Config.LoginRedirect = "/auth/login/google"

Documentation

Index

Constants

View Source
const BROWSERID_SCRIPT = "https://browserid.org/include.js"
View Source
const (
	GoogleOpenIdEndpoint = "https://accounts.google.com/o/openid2/auth"
)
View Source
const VERIFICATION_SERVER = "https://browserid.org/verify"

Variables

View Source
var Config = &AuthConfig{
	CookieName:           "UID",
	CookieExp:            time.Hour * 24 * 14,
	CookieMaxAge:         0,
	LoginRedirect:        "/auth/login",
	LoginSuccessRedirect: "/",
}

Config is the default implementation of Config, and is used by DetaultAuthCallback, Secure, and SecureFunc.

View Source
var DefaultFailure = func(w http.ResponseWriter, r *http.Request, err error) {
	http.Error(w, err.Error(), http.StatusForbidden)
}

DefaultFailure will return an http Forbidden code indicating a failed authentication.

View Source
var DefaultSuccess = func(w http.ResponseWriter, r *http.Request, u User) {
	SetUserCookie(w, r, u.Username())
	http.Redirect(w, r, Config.LoginSuccessRedirect, http.StatusSeeOther)
}

DefaultSuccess will redirect a User, using an http.Redirect, to the Config.LoginSuccessRedirect url upon successful authentication.

View Source
var (
	ErrAuthDeclined = errors.New("Login was unsuccessful or cancelled by User")
)

Functions

func DeleteUserCookie

func DeleteUserCookie(w http.ResponseWriter, r *http.Request)

DeleteUserCookie removes a secure cookie that was created for the user's login session. This effectively logs a user out of the system.

func GetUserCookie

func GetUserCookie(r *http.Request) (user string, err error)

GetUserCookie will get the Username from the http session. If the session is inactive, or if the session has expired, then an error will be returned.

func Secure

func Secure(handler http.Handler) http.Handler

Secure will attempt to verify a user session exists prior to executing the http.Handler ServeHTTP function. If no valid sessions exists, the user will be redirected to the Config.LoginRedirect Url.

func SecureFunc

func SecureFunc(handler http.HandlerFunc) http.HandlerFunc

SecureFunc will attempt to verify a user session exists prior to executing the http.HandlerFunc. If no valid sessions exists, the user will be redirected to the Config.LoginRedirect Url.

func SetUserCookie

func SetUserCookie(w http.ResponseWriter, r *http.Request, user string)

SetUserCookie creates a secure cookie for the given username, indicating the user is authenticated.

Types

type AuthConfig

type AuthConfig struct {
	CookieSecret         []byte
	CookieName           string
	CookieExp            time.Duration
	CookieMaxAge         int
	LoginRedirect        string
	LoginSuccessRedirect string
}

AuthConfig holds configuration parameters used when authenticating a user and creating a secure cookie user session.

type AuthHandler

type AuthHandler struct {

	// Success specifies a function to execute upon successful authentication.
	// If Success is nil, the DefaultSuccess func is used.
	Success func(w http.ResponseWriter, r *http.Request, user User)

	// Failure specifies a function to execute upon failing authentication.
	// If Failure is nil, the DefaultFailure func is used.
	Failure func(w http.ResponseWriter, r *http.Request, err error)
	// contains filtered or unexported fields
}

AuthHandler is an HTTP Handler that authenticates an http.Request using the specified AuthProvider.

func BrowserId

func BrowserId(host string) *AuthHandler

func Github

func Github(client, secret string) *AuthHandler

Github allocates and returns a new AuthHandler, using the GithubProvider.

func Google

func Google(client, secret, redirect string) *AuthHandler

Google allocates and returns a new AuthHandler, using the GoogleProvider.

func New

func New(p AuthProvider) *AuthHandler

New allocates and returns a new AuthHandler, using the specified AuthProvider.

func OpenId

func OpenId(url string) *AuthHandler

OpenId allocates and returns a new AuthHandler, using the OpenIdProvider.

func Twitter

func Twitter(key, secret, callback string) *AuthHandler

Twitter allocates and returns a new AuthHandler, using the TwitterProvider.

func (*AuthHandler) ServeHTTP

func (self *AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles the authentication request and manages the authentication flow.

type AuthProvider

type AuthProvider interface {

	// RedirectRequired returns a boolean value indicating if the request
	// should be redirected to the authentication provider's login screen.
	RedirectRequired(r *http.Request) bool

	// Redirect will do an http.Redirect, sending the user to the authentication
	// provider's login screen.
	Redirect(w http.ResponseWriter, r *http.Request)

	// GetAuthenticatedUser will retrieve the authenticated User from the
	// http.Request object.
	GetAuthenticatedUser(r *http.Request) (User, error)
}

An AuthProvider interface is used by an AuthHandler to authenticate a user over HTTP. Example implementations of an AuthProvider might be OAuth, OpenId, or SAML.

type BrowserIdProvider

type BrowserIdProvider struct {
	Host string
}

func NewBrowserIdProvider

func NewBrowserIdProvider(host string) *BrowserIdProvider

func (*BrowserIdProvider) GetAuthenticatedUser

func (self *BrowserIdProvider) GetAuthenticatedUser(r *http.Request) (User, error)

func (*BrowserIdProvider) Redirect

func (self *BrowserIdProvider) Redirect(w http.ResponseWriter, r *http.Request)

func (*BrowserIdProvider) RedirectRequired

func (self *BrowserIdProvider) RedirectRequired(r *http.Request) bool

type BrowserIdUser

type BrowserIdUser struct {
	Email string
}

func (*BrowserIdUser) EmailAddr

func (self *BrowserIdUser) EmailAddr() string

func (*BrowserIdUser) Fullname

func (self *BrowserIdUser) Fullname() string

func (*BrowserIdUser) Icon

func (self *BrowserIdUser) Icon() string

func (*BrowserIdUser) Password

func (self *BrowserIdUser) Password() string

func (*BrowserIdUser) Provider

func (self *BrowserIdUser) Provider() string

func (*BrowserIdUser) Url

func (self *BrowserIdUser) Url() string

func (*BrowserIdUser) Userid

func (self *BrowserIdUser) Userid() string

func (*BrowserIdUser) Username

func (self *BrowserIdUser) Username() string

type GitHubUser

type GitHubUser struct {
	Id     int64  `json:"id"`
	Email  string `json:"email"`
	Avatar string `json:"avatar_url"`
	Name   string `json:"name"`
	Login  string `json:"login"`
	Link   string `json:"url"`
}

GitHubUser represents a GitHub user object returned by the OAuth2 service.

func (*GitHubUser) EmailAddr

func (u *GitHubUser) EmailAddr() string

func (*GitHubUser) Fullname

func (u *GitHubUser) Fullname() string

func (*GitHubUser) Icon

func (u *GitHubUser) Icon() string

func (*GitHubUser) Password

func (u *GitHubUser) Password() string

func (*GitHubUser) Provider

func (u *GitHubUser) Provider() string

func (*GitHubUser) Url

func (u *GitHubUser) Url() string

func (*GitHubUser) Userid

func (u *GitHubUser) Userid() string

func (*GitHubUser) Username

func (u *GitHubUser) Username() string

type GithubProvider

type GithubProvider struct {
	OAuth2Mixin

	AuthorizeUrl    string
	AccessTokenUrl  string
	UserResourceUrl string
}

GithubProvider is an implementation of Github's Oauth2 protocol. See http://developer.github.com/v3/oauth/

func NewGithubProvider

func NewGithubProvider(clientId, clientSecret string) *GithubProvider

NewGithubProvider allocates and returns a new GithubProvider.

func (*GithubProvider) GetAccessToken

func (self *GithubProvider) GetAccessToken(r *http.Request) (string, error)

GetAccessToken will retrieve the Access Token from the http.Request URL.

func (*GithubProvider) GetAuthenticatedUser

func (self *GithubProvider) GetAuthenticatedUser(r *http.Request) (User, error)

GetAuthenticatedUser will retrieve the Authentication User from the http.Request object.

func (*GithubProvider) Redirect

func (self *GithubProvider) Redirect(w http.ResponseWriter, r *http.Request)

Redirect will do an http.Redirect, sending the user to the Github login screen.

type GoogleProvider

type GoogleProvider struct {
	OAuth2Mixin

	AuthorizeUrl      string
	AccessTokenUrl    string
	UserResourceUrl   string
	UserResourceScope string
}

GoogleProvider is an implementation of Google's Oauth2 for web application flow. See https://developers.google.com/accounts/docs/OAuth2WebServer

func NewGoogleProvider

func NewGoogleProvider(client, secret, redirect string) *GoogleProvider

NewGoogleProvider allocates and returns a new GoogleProvider.

func (*GoogleProvider) GetAccessToken

func (self *GoogleProvider) GetAccessToken(r *http.Request) (string, error)

GetAccessToken will retrieve the Access Token from the http.Request URL.

func (*GoogleProvider) GetAuthenticatedUser

func (self *GoogleProvider) GetAuthenticatedUser(r *http.Request) (User, error)

GetAuthenticatedUser will retrieve the Authentication User from the http.Request object.

func (*GoogleProvider) Redirect

func (self *GoogleProvider) Redirect(w http.ResponseWriter, r *http.Request)

Redirect will do an http.Redirect, sending the user to the Google login screen.

func (*GoogleProvider) RedirectRequired

func (self *GoogleProvider) RedirectRequired(r *http.Request) bool

RedirectRequired returns a boolean value indicating if the request should be redirected to the Google login screen, in order to provide an OAuth Access Token.

type GoogleTokenResp

type GoogleTokenResp struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int32  `json:"expires_in"`
	TokenType   string `json:"token_type"`
}

GoogleTokenResp represents the response data type returned from an Access Token request

type GoogleUser

type GoogleUser struct {
	Id      string `json:"id"`
	Email   string `json:"email"`
	Picture string `json:"picture"`
	Name    string `json:"name"`
	Link    string `json:"link"`
}

GoogleUser represents a Google user object returned by the OAuth2 service.

func (*GoogleUser) EmailAddr

func (u *GoogleUser) EmailAddr() string

func (*GoogleUser) Fullname

func (u *GoogleUser) Fullname() string

func (*GoogleUser) Icon

func (u *GoogleUser) Icon() string

func (*GoogleUser) Password

func (u *GoogleUser) Password() string

func (*GoogleUser) Provider

func (u *GoogleUser) Provider() string

func (*GoogleUser) Url

func (u *GoogleUser) Url() string

func (*GoogleUser) Userid

func (u *GoogleUser) Userid() string

func (*GoogleUser) Username

func (u *GoogleUser) Username() string

type OAuth2Mixin

type OAuth2Mixin struct {
	ClientId     string
	ClientSecret string
	RedirectUrl  string
}

Abstract implementation of OAuth2 for user authentication.

func (*OAuth2Mixin) AuthorizeRedirect

func (self *OAuth2Mixin) AuthorizeRedirect(w http.ResponseWriter, r *http.Request,
	endpoint string, params url.Values)

func (*OAuth2Mixin) GetAccessToken

func (self *OAuth2Mixin) GetAccessToken(endpoint string, params url.Values,
	headers http.Header) (string, error)

func (*OAuth2Mixin) GetAuthenticatedUser

func (self *OAuth2Mixin) GetAuthenticatedUser(endpoint string, accessToken string,
	headers http.Header, resp interface{}) error

func (*OAuth2Mixin) RedirectRequired

func (self *OAuth2Mixin) RedirectRequired(r *http.Request) bool

RedirectRequired returns a boolean value indicating if the request should be redirected to the Provider's login screen, in order to provide an OAuth Access Token.

type OpenIdProvider

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

Base implementation of OpenID for user authentication.

func NewOpenIdProvider

func NewOpenIdProvider(endpoint string) *OpenIdProvider

NewOpenIdProvider allocates and returns a new OpenIdProvider.

func (*OpenIdProvider) GetAuthenticatedUser

func (self *OpenIdProvider) GetAuthenticatedUser(r *http.Request) (User, error)

GetAuthenticatedUser will retrieve the User information from the URL query parameters, per the OpenID specification. If the authentication failed, the function will return an error.

func (*OpenIdProvider) Redirect

func (self *OpenIdProvider) Redirect(w http.ResponseWriter, r *http.Request)

Redirect will send the user to the OpenId Authentication URL

func (*OpenIdProvider) RedirectRequired

func (self *OpenIdProvider) RedirectRequired(r *http.Request) bool

type TwitterProvider

type TwitterProvider struct {
	ConsumerKey    string
	ConsumerSecret string
	CallbackUrl    string
}

TwitterProvider is an implementation of Twitter's OAuth 1.0a protocol. See https://dev.twitter.com/docs/auth/implementing-sign-twitter

func NewTwitterProvider

func NewTwitterProvider(key, secret, callback string) *TwitterProvider

NewTwitterProvider allocates and returns a new TwitterProvider.

func (*TwitterProvider) GetAuthenticatedUser

func (self *TwitterProvider) GetAuthenticatedUser(r *http.Request) (User, error)

func (*TwitterProvider) Redirect

func (self *TwitterProvider) Redirect(w http.ResponseWriter, r *http.Request)

Redirect will send the user to Twitter's Login URL

func (*TwitterProvider) RedirectRequired

func (self *TwitterProvider) RedirectRequired(r *http.Request) bool

type TwitterUser

type TwitterUser struct {
}

type User

type User interface {
	Userid() string
	Username() string
	Password() string
	Fullname() string
	EmailAddr() string
	Icon() string
	Url() string
	Provider() string
}

A User is returned by the AuthProvider upon success authentication.

Directories

Path Synopsis
examples
browserid command
github command
google command
multiple command
openid command
twitter command

Jump to

Keyboard shortcuts

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