oauth2

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2016 License: MIT Imports: 27 Imported by: 0

README

go-oauth2

OAuth2 Provider library written in Go

This is a ported project from OAuth2 Provider that had been written in Node.js with some additional features.

  • Pure implementation in GoLang.
  • Current implementation only supports password_flow & refresh_token_flow.
  • Use JWT.
  • Default buildin with MongoDB.
  • Allow to customize the server.
Example Server
import "github.com/phuc0302/go-oauth2"

// Create server with sandbox mode enable.
server := oauth2.DefaultServer(true)

// Define routing server.
server.Get("/protected", func(c *oauth2.Request, s *oauth2.Security) {
  c.OutputText(utils.Status200(), "This is a protected resources.")
})

// Define who is able to access protected resources.
server.GroupRole("/protected**", "r_user")

// Start server.
server.Run()
Author

Phuc, Tran Huu phuc@fiisionstudio.com

Documentation

Index

Constants

View Source
const (
	Copy    = "copy"
	Delete  = "delete"
	Get     = "get"
	Head    = "head"
	Link    = "link"
	Options = "options"
	Patch   = "patch"
	Post    = "post"
	Purge   = "purge"
	Put     = "put"
	Unlink  = "unlink"
)

HTTP Methods.

View Source
const (
	// For apps running on a web server
	AuthorizationCodeGrant = "authorization_code"

	// For application access
	ClientCredentialsGrant = "client_credentials"

	// For browser-based or mobile apps
	ImplicitGrant = "implicit"

	// For logging in with a username and password
	PasswordGrant = "password"

	// Should allow refresh token or not
	RefreshTokenGrant = "refresh_token"
)

OAuth2.0 flows.

View Source
const (
	TableAccessToken  = "oauth_access_token"
	TableClient       = "oauth_client"
	TableRefreshToken = "oauth_refresh_token"
	TableUser         = "oauth_user"
)

OAuth2 tables.

View Source
const (
	InvalidParameter = "Invalid \"%s\" parameter."
)

Error messages.

Variables

View Source
var (
	// Global public config's instance.
	Cfg Config

	// Global public token store's instance.
	Store TokenStore
)

Global variables.

Functions

func CreateConfig added in v0.1.8

func CreateConfig(configFile string)

CreateConfig generates a default configuration file.

func GetEnv

func GetEnv(key string) string

GetEnv retrieves value from environment.

func SetEnv

func SetEnv(key string, value string)

SetEnv persists key-value to environment.

Types

type AuthorizationGrant added in v0.1.9

type AuthorizationGrant struct {
}

func (*AuthorizationGrant) HandleForm added in v0.1.9

func (a *AuthorizationGrant) HandleForm(c *RequestContext, s *OAuthContext)

*

  • Check Request Params *
  • @param {Function} done
  • @this OAuth

type Client added in v0.1.8

type Client interface {

	// Return client's ID.
	ClientID() string

	// Return client's secret.
	ClientSecret() string

	// Return client's allowed grant types.
	GrantTypes() []string

	// Return client's registered redirect URIs.
	RedirectURIs() []string
}

////////////////////////////////////////////////////////////////////////////////////////////////// Client describes a client's characteristic.

type Config added in v0.1.1

type Config struct {
	// Server
	Host    string `json:"host"`
	Port    int    `json:"port"`
	TLSPort int    `json:"tls_port"`

	// Header
	HeaderSize    int           `json:"header_size"`    // In KB
	MultipartSize int64         `json:"multipart_size"` // In MB
	ReadTimeout   time.Duration `json:"timeout_read"`   // In seconds
	WriteTimeout  time.Duration `json:"timeout_write"`  // In seconds

	// HTTP Method
	AllowMethods  []string          `json:"allow_methods"`
	RedirectPaths map[string]string `json:"redirect_paths"`
	StaticFolders map[string]string `json:"static_folders"`

	// Log
	LogLevel     string `json:"log_level"`
	SlackURL     string `json:"slack_url"`
	SlackIcon    string `json:"slack_icon"`
	SlackUser    string `json:"slack_user"`
	SlackChannel string `json:"slack_channel"`

	// OAuth2.0
	GrantTypes                []string      `json:"grant_types"`
	PrivateKey                []byte        `json:"private_key"`
	AllowRefreshToken         bool          `json:"allow_refresh_token"`
	AccessTokenDuration       time.Duration `json:"access_token_duration"`       // In seconds
	RefreshTokenDuration      time.Duration `json:"refresh_token_duration"`      // In seconds
	AuthorizationCodeDuration time.Duration `json:"authorization_code_duration"` // In seconds
}

Config describes a configuration object that will be used during application life time.

func LoadConfig added in v0.1.8

func LoadConfig(configFile string) Config

LoadConfig retrieves previous configuration from file.

type ContextHandler added in v0.1.8

type ContextHandler func(request *RequestContext, security *OAuthContext)

Type alias

type DefaultClient

type DefaultClient struct {
	ID        bson.ObjectId `bson:"_id"`
	Secret    bson.ObjectId `bson:"client_secret"`
	Grants    []string      `bson:"grant_types,omitempty"`
	Redirects []string      `bson:"redirect_uris,omitempty"`
}

DefaultClient describes a mongodb client.

func (*DefaultClient) ClientID

func (a *DefaultClient) ClientID() string

ClientID returns client_id.

func (*DefaultClient) ClientSecret

func (a *DefaultClient) ClientSecret() string

ClientSecret returns client_secret.

func (*DefaultClient) GrantTypes

func (a *DefaultClient) GrantTypes() []string

GrantTypes returns grant_types.

func (*DefaultClient) RedirectURIs

func (a *DefaultClient) RedirectURIs() []string

RedirectURIs returns redirect_uris.

type DefaultMongoStore

type DefaultMongoStore struct {
}

DefaultMongoStore describes a mongodb store.

func (*DefaultMongoStore) CreateAccessToken

func (d *DefaultMongoStore) CreateAccessToken(clientID string, userID string, createdTime time.Time, expiredTime time.Time) Token

CreateAccessToken returns new access_token.

func (*DefaultMongoStore) CreateRefreshToken

func (d *DefaultMongoStore) CreateRefreshToken(clientID string, userID string, createdTime time.Time, expiredTime time.Time) Token

CreateRefreshToken returns new refresh_token.

func (*DefaultMongoStore) DeleteAccessToken

func (d *DefaultMongoStore) DeleteAccessToken(token Token)

DeleteAccessToken deletes access_token.

func (*DefaultMongoStore) DeleteRefreshToken

func (d *DefaultMongoStore) DeleteRefreshToken(token Token)

DeleteRefreshToken deletes refresh_token.

func (*DefaultMongoStore) FindAccessToken

func (d *DefaultMongoStore) FindAccessToken(token string) Token

FindAccessToken returns access_token.

func (*DefaultMongoStore) FindAccessTokenWithCredential

func (d *DefaultMongoStore) FindAccessTokenWithCredential(clientID string, userID string) Token

FindAccessTokenWithCredential returns access_token associated with client_id and user_id.

func (*DefaultMongoStore) FindClientWithCredential

func (d *DefaultMongoStore) FindClientWithCredential(clientID string, clientSecret string) Client

FindClientWithCredential returns client with client_id and client_secret.

func (*DefaultMongoStore) FindClientWithID

func (d *DefaultMongoStore) FindClientWithID(clientID string) Client

FindClientWithID returns user associated with client_id.

func (*DefaultMongoStore) FindRefreshToken

func (d *DefaultMongoStore) FindRefreshToken(token string) Token

FindRefreshToken returns refresh_token.

func (*DefaultMongoStore) FindRefreshTokenWithCredential

func (d *DefaultMongoStore) FindRefreshTokenWithCredential(clientID string, userID string) Token

FindRefreshTokenWithCredential returns refresh_token associated with client_id and user_id.

func (*DefaultMongoStore) FindUserWithClient

func (d *DefaultMongoStore) FindUserWithClient(clientID string, clientSecret string) User

FindUserWithClient returns user associated with client_id and client_secret.

func (*DefaultMongoStore) FindUserWithCredential

func (d *DefaultMongoStore) FindUserWithCredential(username string, password string) User

FindUserWithCredential returns user associated with username and password.

func (*DefaultMongoStore) FindUserWithID

func (d *DefaultMongoStore) FindUserWithID(userID string) User

FindUserWithID returns user with user_id.

type DefaultToken

type DefaultToken struct {
	ID      bson.ObjectId `bson:"_id"`
	User    bson.ObjectId `bson:"user_id,omitempty"`
	Client  bson.ObjectId `bson:"client_id,omitempty"`
	Created time.Time     `bson:"created_time,omitempty"`
	Expired time.Time     `bson:"expired_time,omitempty"`
}

DefaultToken describes a mongodb Token.

func (*DefaultToken) ClientID

func (t *DefaultToken) ClientID() string

ClientID returns client_id.

func (*DefaultToken) CreatedTime

func (t *DefaultToken) CreatedTime() time.Time

CreatedTime returns created_time.

func (*DefaultToken) ExpiredTime

func (t *DefaultToken) ExpiredTime() time.Time

ExpiredTime returns expired_time.

func (*DefaultToken) IsExpired

func (t *DefaultToken) IsExpired() bool

IsExpired validate if this token is expired or not.

func (*DefaultToken) Token

func (t *DefaultToken) Token() string

Token returns token.

func (*DefaultToken) UserID

func (t *DefaultToken) UserID() string

UserID returns user_id.

type DefaultUser

type DefaultUser struct {
	ID    bson.ObjectId `bson:"_id"`
	User  string        `bson:"username,omitempty"`
	Pass  string        `bson:"password,omitempty"`
	Roles []string      `bson:"roles,omitempty"`

	FacebookID    string `bson:"facebook_id,omitempty"`
	FacebookToken string `bson:"facebook_token,omitempty"`
}

DefaultUser describes a mongodb user.

func (*DefaultUser) Password

func (a *DefaultUser) Password() string

Password returns password.

func (*DefaultUser) UserID

func (a *DefaultUser) UserID() string

UserID returns user_id.

func (*DefaultUser) UserRoles

func (a *DefaultUser) UserRoles() []string

UserRoles returns user's roles.

func (*DefaultUser) Username

func (a *DefaultUser) Username() string

Username returns user's username.

type GroupHandler added in v0.1.8

type GroupHandler func(server *Server)

type OAuthContext added in v0.1.8

type OAuthContext struct {

	// Registered user. Always available.
	User User
	// Registered client. Always available.
	Client Client
	// Access token that had been given to user. Always available.
	AccessToken Token
	// Refresh token that had been given to user. Might not be available all the time.
	RefreshToken Token
}

////////////////////////////////////////////////////////////////////////////////////////////////// OAuthContext describes a user's oauth scope.

type RequestContext added in v0.1.8

type RequestContext struct {
	Method      string
	Path        string
	Header      map[string]string
	PathParams  map[string]string
	QueryParams map[string]string
	// contains filtered or unexported fields
}

////////////////////////////////////////////////////////////////////////////////////////////////// RequestContext describes a HTTP URL request scope.

func (*RequestContext) BasicAuth added in v0.1.8

func (c *RequestContext) BasicAuth() (username string, password string, ok bool)

BasicAuth returns username & password.

func (*RequestContext) BindForm added in v0.1.8

func (c *RequestContext) BindForm(inputForm interface{}) error

BindForm converts urlencode/multipart form to object.

func (*RequestContext) BindJSON added in v0.1.8

func (c *RequestContext) BindJSON(jsonObject interface{}) error

BindJSON converts json data to object.

func (*RequestContext) MultipartFile added in v0.1.8

func (c *RequestContext) MultipartFile(name string) (multipart.File, *multipart.FileHeader, error)

MultipartFile returns an uploaded file by name.

func (*RequestContext) OutputError added in v0.1.8

func (c *RequestContext) OutputError(status *util.Status)

OutputError returns an error JSON.

func (*RequestContext) OutputHTML added in v0.1.8

func (c *RequestContext) OutputHTML(filePath string, model interface{})

OutputHTML returns a HTML page.

func (*RequestContext) OutputHeader added in v0.1.8

func (c *RequestContext) OutputHeader(headerName string, headerValue string)

OutputHeader returns an additional header.

func (*RequestContext) OutputJSON added in v0.1.8

func (c *RequestContext) OutputJSON(status *util.Status, model interface{})

OutputJSON returns a JSON.

func (*RequestContext) OutputRedirect added in v0.1.8

func (c *RequestContext) OutputRedirect(status *util.Status, url string)

OutputRedirect returns a redirect instruction.

func (*RequestContext) OutputText added in v0.1.8

func (c *RequestContext) OutputText(status *util.Status, data string)

OutputText returns a string.

type Server

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

Server describes server object.

func CreateServer

func CreateServer(tokenStore TokenStore, isSandbox bool) *Server

////////////////////////////////////////////////////////////////////////////////////////////////// CreateServer returns a server with custom components.

func DefaultServer

func DefaultServer(isSandbox bool) *Server

DefaultServer returns a server with build in components.

func (*Server) Copy

func (s *Server) Copy(urlPattern string, handler ContextHandler)

Copy routes copy request to registered handler.

func (*Server) Delete

func (s *Server) Delete(urlPattern string, handler ContextHandler)

Delete routes delete request to registered handler.

func (*Server) Get

func (s *Server) Get(urlPattern string, handler ContextHandler)

Get routes get request to registered handler.

func (*Server) GroupRoles added in v0.1.3

func (s *Server) GroupRoles(groupPath string, roles ...string)

////////////////////////////////////////////////////////////////////////////////////////////////// GroupRoles binds user's roles to all url with same prefix.

func (*Server) GroupRoute

func (s *Server) GroupRoute(urlPrefix string, handler GroupHandler)

GroupRoute routes all url with same prefix.

func (*Server) Head

func (s *Server) Head(urlPattern string, handler ContextHandler)

Head routes head request to registered handler.

func (s *Server) Link(urlPattern string, handler ContextHandler)

Link routes link request to registered handler.

func (*Server) Options

func (s *Server) Options(urlPattern string, handler ContextHandler)

Options routes options request to registered handler.

func (*Server) Patch

func (s *Server) Patch(urlPattern string, handler ContextHandler)

Patch routes patch request to registered handler.

func (*Server) Post

func (s *Server) Post(urlPattern string, handler ContextHandler)

Post routes post request to registered handler.

func (*Server) Purge

func (s *Server) Purge(urlPattern string, handler ContextHandler)

Purge routes purge request to registered handler.

func (*Server) Put

func (s *Server) Put(urlPattern string, handler ContextHandler)

Put routes put request to registered handler.

func (*Server) Run

func (s *Server) Run()

////////////////////////////////////////////////////////////////////////////////////////////////// Run will start server on http port.

func (*Server) RunTLS

func (s *Server) RunTLS(certFile string, keyFile string)

RunTLS will start server on https port.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

////////////////////////////////////////////////////////////////////////////////////////////////// ServeHTTP handle HTTP request and HTTP response.

func (s *Server) Unlink(urlPattern string, handler ContextHandler)

Unlink routes unlink request to registered handler.

type ServerRoute added in v0.1.8

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

ServerRoute describes a route component.

type ServerRouter added in v0.1.8

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

/ ServerRouter describes a router component implementation.

type TestUnit added in v0.1.6

type TestUnit struct {
	Session  *mgo.Session
	Database *mgo.Database

	Client Client
	User1  User
	User2  User

	Username     string
	Password     string
	UserID       bson.ObjectId
	ClientID     bson.ObjectId
	ClientSecret bson.ObjectId
	CreatedTime  time.Time
}

TestUnit describes an implementation for OAuth2 unit test.

func (*TestUnit) Setup added in v0.1.6

func (u *TestUnit) Setup()

Setup initializes environment.

func (*TestUnit) Teardown added in v0.1.6

func (u *TestUnit) Teardown()

Teardown cleans up environment.

type Token added in v0.1.8

type Token interface {

	// Return client's ID.
	ClientID() string

	// Return user's ID.
	UserID() string

	// Return token.
	Token() string

	// Check if token is expired or not.
	IsExpired() bool

	// Return token's created time.
	CreatedTime() time.Time

	// Return token's expired time.
	ExpiredTime() time.Time
}

////////////////////////////////////////////////////////////////////////////////////////////////// Token describes a token's characteristic, it can be either access token or refresh token.

type TokenGrant

type TokenGrant struct {
}

TokenGrant describes a token grant controller.

func (*TokenGrant) HandleForm

func (g *TokenGrant) HandleForm(c *RequestContext, s *OAuthContext)

HandleForm validates authentication form.

type TokenResponse

type TokenResponse struct {
	TokenType    string `json:"token_type,omitempty"`
	AccessToken  string `json:"access_token,omitempty"`
	ExpiresIn    int64  `json:"expires_in,omitempty"`
	RefreshToken string `json:"refresh_token,omitempty"`

	Roles []string `json:"roles,omitempty"`
}

////////////////////////////////////////////////////////////////////////////////////////////////// TokenResponse describes a granted response that will be returned to client.

type TokenStore added in v0.1.1

type TokenStore interface {

	// User
	FindUserWithID(userID string) User
	FindUserWithClient(clientID string, clientSecret string) User
	FindUserWithCredential(username string, password string) User

	// Client
	FindClientWithID(clientID string) Client
	FindClientWithCredential(clientID string, clientSecret string) Client

	// Access Token
	FindAccessToken(token string) Token
	FindAccessTokenWithCredential(clientID string, userID string) Token
	CreateAccessToken(clientID string, userID string, createdTime time.Time, expiredTime time.Time) Token
	DeleteAccessToken(token Token)

	// Refresh Token
	FindRefreshToken(token string) Token
	FindRefreshTokenWithCredential(clientID string, userID string) Token
	CreateRefreshToken(clientID string, userID string, createdTime time.Time, expiredTime time.Time) Token
	DeleteRefreshToken(token Token)
}

////////////////////////////////////////////////////////////////////////////////////////////////// TokenStore describes a token store's characteristic.

type User added in v0.1.8

type User interface {

	// Return user's ID.
	UserID() string

	// Return user's username.
	Username() string

	// Return user's password.
	Password() string

	// Return user's roles.
	UserRoles() []string
}

////////////////////////////////////////////////////////////////////////////////////////////////// User describes an user's characteristic.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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