auth

package module
v0.0.0-...-61fa54b Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2013 License: MIT Imports: 13 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.

THIS LIBRARY IS BEING ACTIVELY DEVELOPED. THE API IS CHANGING WEEKLY.

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
  • Bitbucket OAuth 1.0a demo

See the multi-provider demo application to provide your users multiple login options.

We plan to add support for the following providers:

  • Facebook
  • LinkedIn

Sample Code

Example program using the Github OAuth auth provider:

// Set the default authentication configuration parameters
auth.Config.CookieSecret         = []byte("asdfasdfasfasdfasdfafsd")
auth.Config.LoginRedirect        = "/auth/login" // send user here to login
auth.Config.LoginSuccessRedirect = "/private"    // send user here post-login
auth.Config.CookieSecure         = false         // for local-testing only

// Create your login handler
githubHandler := auth.Github(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))

It is important to note that we have set auth.Config.CookieSecure to false because we are testing locally, without using SSL. In production this flag should ALWAYS be set to true and used in conjunction with SSL.

User data

The auth.SecureFunc wraps a standard http.HandlerFunc and injects the username into the http request's r.URL.User.Username() field:

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

If you want additional user data you must implement our custom handler, and wrap it with the auth.SecureUserFunc. This adds an additional User parameter to your method signature that provides the full set of available user data:

func Private(w http.ResponseWriter, r *http.Request, u auth.User) {
	username := u.Id()
	fullname := u.Name()
	avatar := u.Picture()
	email := u.Email()
	...
}

http.HandleFunc("/foo", auth.SecureUserFunc(Private))

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.CookieSecure set the cookie's secure flag (true/false) true
auth.Config.CookieHttpOnly set the cookie's HttpOnly flag (true/false) true
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 (
	GoogleOpenIdEndpoint = "https://accounts.google.com/o/openid2/auth"
)

Variables

View Source
var (
	ErrSessionExpired      = errors.New("User session Expired")
	ErrInvalidCookieFormat = errors.New("Invalid Cookie Format")
)

Error messages related to the Secure Cookie parsing and verification

View Source
var Config = &AuthConfig{
	CookieName:           "_sess",
	CookieExp:            time.Hour * 24 * 14,
	CookieMaxAge:         0,
	CookieSecure:         true,
	CookieHttpOnly:       true,
	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, t Token) {
	SetUserCookie(w, r, u)
	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 DeleteUserCookieName

func DeleteUserCookieName(w http.ResponseWriter, r *http.Request, name string)

DeleteUserCookieName removes a secure cookie with the specified name.

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 SecureGuest

func SecureGuest(handler SecureHandlerFunc) http.HandlerFunc

SecureGuest will attempt to retireve authenticated User details from the current session when invoking the auth.SecureHandlerFunc function. If no User details are found the handler will allow the user to proceed as a guest, which means the User details will be nil.

This function is intended for pages that are Publicly visible, but display additional details for authenticated users.

func SecureUser

func SecureUser(handler SecureHandlerFunc) http.HandlerFunc

SecureUser will attempt to verify a user session exists prior to executing the auth.SecureHandlerFunc function. If no valid sessions exists, the user will be redirected to a login URL.

func SetUserCookie

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

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

func SetUserCookieOpts

func SetUserCookieOpts(w http.ResponseWriter, cookie *http.Cookie, user User)

SetUserCookieOpts creates a secure cookie for the given User and with the specified cookie options.

Types

type AuthConfig

type AuthConfig struct {
	CookieSecret         []byte
	CookieName           string
	CookieExp            time.Duration
	CookieMaxAge         int
	CookieSecure         bool
	CookieHttpOnly       bool
	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, u User, t Token)

	// 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 Bitbucket

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

Bitbucket allocates and returns a new AuthHandler, using the BitbucketProvider.

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(w http.ResponseWriter, r *http.Request) (User, Token, 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 BitbucketProvider

type BitbucketProvider struct {
	OAuth1Mixin
}

BitbucketProvider is an implementation of Bitbucket's Oauth1.0a protocol. See https://confluence.atlassian.com/display/BITBUCKET/OAuth+on+Bitbucket

func NewBitbucketProvider

func NewBitbucketProvider(key, secret, callback string) *BitbucketProvider

NewBitbucketProvider allocates and returns a new BitbucketProvider.

func (*BitbucketProvider) GetAuthenticatedUser

func (self *BitbucketProvider) GetAuthenticatedUser(w http.ResponseWriter, r *http.Request) (User, Token, error)

GetAuthenticatedUser will upgrade the oauth_token to an access token, and invoke the appropriate Bitbucket REST API call to get the User's information.

type BitbucketUser

type BitbucketUser struct {
	UserId        string `json:"username"`
	UserPicture   string `json:"avatar"`
	UserLastName  string `json:"last_name"`
	UserFirstName string `json:"first_name"`
}

func (*BitbucketUser) Email

func (u *BitbucketUser) Email() string

func (*BitbucketUser) Id

func (u *BitbucketUser) Id() string
func (u *BitbucketUser) Link() string

func (*BitbucketUser) Name

func (u *BitbucketUser) Name() string

func (*BitbucketUser) Org

func (u *BitbucketUser) Org() string

func (*BitbucketUser) Picture

func (u *BitbucketUser) Picture() string

func (*BitbucketUser) Provider

func (u *BitbucketUser) Provider() string

type GitHubUser

type GitHubUser struct {
	UserEmail    interface{} `json:"email"`
	UserName     interface{} `json:"name"`
	UserGravatar interface{} `json:"gravatar_id"`
	UserCompany  interface{} `json:"company"`
	UserLink     interface{} `json:"html_url"`
	UserLogin    string      `json:"login"`
}

func (*GitHubUser) Email

func (u *GitHubUser) Email() string

func (*GitHubUser) Id

func (u *GitHubUser) Id() string
func (u *GitHubUser) Link() string

func (*GitHubUser) Name

func (u *GitHubUser) Name() string

func (*GitHubUser) Org

func (u *GitHubUser) Org() string

func (*GitHubUser) Picture

func (u *GitHubUser) Picture() string

func (*GitHubUser) Provider

func (u *GitHubUser) Provider() string

type GithubProvider

type GithubProvider struct {
	OAuth2Mixin
}

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) GetAuthenticatedUser

func (self *GithubProvider) GetAuthenticatedUser(w http.ResponseWriter, r *http.Request) (User, Token, 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
}

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) GetAuthenticatedUser

func (self *GoogleProvider) GetAuthenticatedUser(w http.ResponseWriter, r *http.Request) (User, Token, 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.

type GoogleUser

type GoogleUser struct {
	UserId      string `json:"id"`
	UserEmail   string `json:"email"`
	UserPicture string `json:"picture"`
	UserName    string `json:"name"`
	UserLink    string `json:"link"`
}

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

func (*GoogleUser) Email

func (u *GoogleUser) Email() string

func (*GoogleUser) Id

func (u *GoogleUser) Id() string
func (u *GoogleUser) Link() string

func (*GoogleUser) Name

func (u *GoogleUser) Name() string

func (*GoogleUser) Org

func (u *GoogleUser) Org() string

func (*GoogleUser) Picture

func (u *GoogleUser) Picture() string

func (*GoogleUser) Provider

func (u *GoogleUser) Provider() string

type OAuth1Mixin

type OAuth1Mixin struct {
	oauth1.Consumer
}

Abstract implementation of OAuth2 for user authentication.

func (*OAuth1Mixin) AuthorizeRedirect

func (self *OAuth1Mixin) AuthorizeRedirect(w http.ResponseWriter, r *http.Request, endpoint string) error

Redirects the User to the OAuth1.0a provider's Login Screen. A RequestToken is requested from the Provider, and included in the URL's oauth_token param.

A Successful Login / Authorization should return both the oauth_token and the oauth_verifier to the callback URL.

func (*OAuth1Mixin) AuthorizeToken

func (self *OAuth1Mixin) AuthorizeToken(w http.ResponseWriter, r *http.Request) (*oauth1.AccessToken, error)

AuthorizeToken trades the Verification Code (oauth_verification) for an Access Token.

func (*OAuth1Mixin) GetAuthenticatedUser

func (self *OAuth1Mixin) GetAuthenticatedUser(endpoint string, token *oauth1.AccessToken, resp interface{}) error

func (*OAuth1Mixin) Redirect

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

Redirect will do an http.Redirect, sending the user to the Provider's login screen.

func (*OAuth1Mixin) RedirectRequired

func (self *OAuth1Mixin) 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 Verifier Token.

type OAuth2Mixin

type OAuth2Mixin struct {
	oauth2.Client
}

Abstract implementation of OAuth2 for user authentication.

func (*OAuth2Mixin) AuthorizeRedirect

func (self *OAuth2Mixin) AuthorizeRedirect(w http.ResponseWriter, r *http.Request, scope string)

Redirects the User to the Login Screen

func (*OAuth2Mixin) GetAccessToken

func (self *OAuth2Mixin) GetAccessToken(r *http.Request) (*oauth2.Token, error)

Exchanges the verifier for an OAuth2 Access Token.

func (*OAuth2Mixin) GetAuthenticatedUser

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

Gets the Authenticated User

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(w http.ResponseWriter, r *http.Request) (User, Token, 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 SecureHandlerFunc

type SecureHandlerFunc func(w http.ResponseWriter, r *http.Request, u User)

SecureHandlerFunc type is an adapter that extends the standard http.HandlerFunc to include the authenticated User details.

type Token

type Token interface {
	Token() string
}

Passes back the OAuth Token. This will likely be the oauth2.Token or the oauth1.AccessToken... will need to cast to the appropriate value if you need specific fields (for now).

type TwitterProvider

type TwitterProvider struct {
	OAuth1Mixin
}

TwitterProvider is an implementation of Twitters's Oauth1.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 BitbucketProvider.

func (*TwitterProvider) GetAuthenticatedUser

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

GetAuthenticatedUser will upgrade the oauth_token to an access token, and invoke the appropriate Twitter REST API call to get the User's information.

type TwitterUser

type TwitterUser struct {
	UserId string `json:"screen_name"`
}

func (*TwitterUser) Email

func (u *TwitterUser) Email() string

func (*TwitterUser) Id

func (u *TwitterUser) Id() string
func (u *TwitterUser) Link() string

func (*TwitterUser) Name

func (u *TwitterUser) Name() string

func (*TwitterUser) Org

func (u *TwitterUser) Org() string

func (*TwitterUser) Picture

func (u *TwitterUser) Picture() string

func (*TwitterUser) Provider

func (u *TwitterUser) Provider() string

type User

type User interface {
	Id() string       // Unique identifier of the user
	Provider() string // Name of the Authentication Provider (ie google, github)
	Name() string     // Name of the User (ie lastname, firstname)
	Email() string    // Email Address of the User
	Org() string      // Company or Organization the User belongs to
	Picture() string  // URL of the User's Profile picture
	Link() string     // URL of the User's Profile page
}

A User is returned by the AuthProvider upon success authentication.

func GetUserCookie

func GetUserCookie(r *http.Request) (User, error)

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

func GetUserCookieName

func GetUserCookieName(r *http.Request, name string) (User, error)

GetUserCookieName will get the User data from the http session for the specified secure cookie. If the session is inactive, or if the session has expired, then an error will be returned.

Jump to

Keyboard shortcuts

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