osin

package module
v0.0.0-...-07a015b Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2014 License: BSD-3-Clause Imports: 8 Imported by: 0

README

OSIN

Golang OAuth2 server library

OSIN is an OAuth2 server library for the Go language, as specified at http://tools.ietf.org/html/rfc6749.

Using it, you can build your own OAuth2 authentication service.

The library implements the majority of the specification, like authorization and token endpoints, and authorization code, implicit, resource owner and client credentials grant types.

Dependencies
Example Server
import "github.com/RangelReale/osin"

// TestStorage implements the "osin.Storage" interface
server := osin.NewServer(osin.NewServerConfig(), &TestStorage{})
output := osin.NewResponseOutputJSON()

// Authorization code endpoint
http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
	resp := server.NewResponse()
	if ar := server.HandleAuthorizeRequest(resp, r); ar != nil {
		
		// HANDLE LOGIN PAGE HERE
		
		ar.Authorized = true
		server.FinishAuthorizeRequest(resp, r, ar)
	}
	output.Output(resp, w, r)
})

// Access token endpoint
http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
	resp := server.NewResponse()
	if ar := server.HandleAccessRequest(resp, r); ar != nil {
		ar.Authorized = true
		server.FinishAccessRequest(resp, r, ar)
	}
	output.Output(resp, w, r)
})

http.ListenAndServe(":14000", nil)
Example Access

Open in your web browser:

http://localhost:14000/authorize?response_type=code&client_id=1234&redirect_url=http%3A%2F%2Flocalhost%3A14000%2Fappauth%2Fcode
License

The code is licensed using "New BSD" license.

Author

Rangel Reale

Documentation

Index

Constants

View Source
const (
	AUTHORIZATION_CODE AccessRequestType = "authorization_code"
	REFRESH_TOKEN                        = "refresh_token"
	PASSWORD                             = "password"
	FB_TOKEN                             = "facebook"
	CLIENT_CREDENTIALS                   = "client_credentials"
	IMPLICIT                             = "__implicit"
)
View Source
const (
	E_INVALID_REQUEST           = "invalid_request"
	E_UNAUTHORIZED_CLIENT       = "unauthorized_client"
	E_ACCESS_DENIED             = "access_denied"
	E_UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type"
	E_INVALID_SCOPE             = "invalid_scope"
	E_SERVER_ERROR              = "server_error"
	E_TEMPORARILY_UNAVAILABLE   = "temporarily_unavailable"
	E_UNSUPPORTED_GRANT_TYPE    = "unsupported_grant_type"
	E_INVALID_GRANT             = "invalid_grant"
	E_INVALID_CLIENT            = "invalid_client"
)

Variables

This section is empty.

Functions

func CheckBasicAuth

func CheckBasicAuth(r *http.Request) (*BasicAuth, *HttpError)

CheckBasicAuth reads Basic authorization from the Authorization header.

func CheckClientAuth

func CheckClientAuth(r *http.Request, params objx.Map, useparams bool) (*BasicAuth, *HttpError)

ChecClientAuth checks for client_id and client_secret in the Authorization header and (if useparams is true) request parameters.

func GetValidAuth

func GetValidAuth(request *http.Request, params objx.Map, allowSecretInParams bool) (*BasicAuth, *HttpError)

GetValidAuth loads authorization using CheckClientAuth, then ensures that the authorization is valid. It returns a *HttpError if there are any problems with the request.

Types

type AccessData

type AccessData interface {
	GetClient() Client
	SetClient(Client)

	GetAuthorizeData() AuthorizeData
	SetAuthorizeData(AuthorizeData)

	GetAccessData() AccessData
	SetAccessData(AccessData)

	GetAccessToken() string
	SetAccessToken(string)

	GetRefreshToken() string
	SetRefreshToken(string)

	GetExpiresIn() int32
	SetExpiresIn(int32)

	GetScope() string
	SetScope(string)

	GetRedirectUri() string
	SetRedirectUri(string)

	GetCreatedAt() time.Time
	SetCreatedAt(time.Time)

	ExpiresAt() time.Time

	IsExpired() bool
}

AccessData is any struct that impelements getters and setters for access information.

type AccessRequest

type AccessRequest struct {
	Type          AccessRequestType
	Code          string
	Client        Client
	AuthorizeData AuthorizeData
	AccessData    AccessData
	RedirectUri   string
	Scope         string
	Username      string
	Password      string

	// Set if request is authorized
	Authorized bool

	// Token expiration in seconds. Change if different from default
	Expiration int32

	// Set if a refresh token should be generated
	GenerateRefresh bool
}

type AccessRequestType

type AccessRequestType string

type AccessTokenGen

type AccessTokenGen interface {
	GenerateAccessToken(generaterefresh bool) (accesstoken string, refreshtoken string, err *HttpError)
}

Access token generator interface

type AccessTokenGenDefault

type AccessTokenGenDefault struct {
}

Default authorization token generator

func (*AccessTokenGenDefault) GenerateAccessToken

func (a *AccessTokenGenDefault) GenerateAccessToken(generaterefresh bool) (accesstoken string, refreshtoken string, err *HttpError)

type AllowedAccessType

type AllowedAccessType []AccessRequestType

func (AllowedAccessType) Exists

Checks if the type exists in the list

type AllowedAuthorizeType

type AllowedAuthorizeType []AuthorizeRequestType

Helper allowing objects

func (AllowedAuthorizeType) Exists

Checks if the type exists in the list

type AuthorizeData

type AuthorizeData interface {
	GetClient() Client
	SetClient(Client)

	GetCode() string
	SetCode(string)

	GetExpiresIn() int32
	SetExpiresIn(int32)

	GetScope() string
	SetScope(string)

	GetRedirectUri() string
	SetRedirectUri(string)

	GetState() string
	SetState(string)

	GetCreatedAt() time.Time
	SetCreatedAt(time.Time)

	IsExpired() bool

	ExpiresAt() time.Time
}

AuthorizeData is any struct that implements getters and setters for authorization data, as well as expiration methods.

type AuthorizeRequest

type AuthorizeRequest struct {
	Type        AuthorizeRequestType
	Client      Client
	Scope       string
	RedirectUri string
	State       string

	// Set if request is authorized
	Authorized bool

	// Token expiration in seconds. Change if different from default.
	// If type = TOKEN, this expiration will be for the ACCESS token.
	Expiration int32
}

Authorize request information

type AuthorizeRequestType

type AuthorizeRequestType string
const (
	CODE  AuthorizeRequestType = "code"
	TOKEN                      = "token"
)

type AuthorizeTokenGen

type AuthorizeTokenGen interface {
	GenerateAuthorizeToken() (string, *HttpError)
}

Authorization token generator interface

type AuthorizeTokenGenDefault

type AuthorizeTokenGenDefault struct {
}

Default authorization token generator

func (*AuthorizeTokenGenDefault) GenerateAuthorizeToken

func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken() (ret string, err *HttpError)

type BasicAccessData

type BasicAccessData struct {
	// Client information
	Client Client

	// Authorize data, for authorization code
	AuthorizeData AuthorizeData

	// Previous access data, for refresh token
	AccessData AccessData

	// Access token
	AccessToken string

	// Refresh Token. Can be blank
	RefreshToken string

	// Token expiration in seconds
	ExpiresIn int32

	// Requested scope
	Scope string

	// Redirect Uri from request
	RedirectUri string

	// Date created
	CreatedAt time.Time
}

BasicAccessData is a very basic struct type that implements AccessData. Most likely, this doesn't contain enough information for your needs (at minimum, it should have data about the user). You should embed this struct into your own struct, so that you can add whatever extra data you need.

func (*BasicAccessData) ExpiresAt

func (data *BasicAccessData) ExpiresAt() time.Time

ExpiresAt returns this AccessData's expiration timestamp.

func (*BasicAccessData) GetAccessData

func (data *BasicAccessData) GetAccessData() AccessData

func (*BasicAccessData) GetAccessToken

func (data *BasicAccessData) GetAccessToken() string

func (*BasicAccessData) GetAuthorizeData

func (data *BasicAccessData) GetAuthorizeData() AuthorizeData

func (*BasicAccessData) GetClient

func (data *BasicAccessData) GetClient() Client

func (*BasicAccessData) GetCreatedAt

func (data *BasicAccessData) GetCreatedAt() time.Time

func (*BasicAccessData) GetExpiresIn

func (data *BasicAccessData) GetExpiresIn() int32

func (*BasicAccessData) GetRedirectUri

func (data *BasicAccessData) GetRedirectUri() string

func (*BasicAccessData) GetRefreshToken

func (data *BasicAccessData) GetRefreshToken() string

func (*BasicAccessData) GetScope

func (data *BasicAccessData) GetScope() string

func (*BasicAccessData) IsExpired

func (data *BasicAccessData) IsExpired() bool

IsExpired returns true if this AccessData is expired, false otherwise.

func (*BasicAccessData) SetAccessData

func (data *BasicAccessData) SetAccessData(accessData AccessData)

func (*BasicAccessData) SetAccessToken

func (data *BasicAccessData) SetAccessToken(token string)

func (*BasicAccessData) SetAuthorizeData

func (data *BasicAccessData) SetAuthorizeData(authData AuthorizeData)

func (*BasicAccessData) SetClient

func (data *BasicAccessData) SetClient(client Client)

func (*BasicAccessData) SetCreatedAt

func (data *BasicAccessData) SetCreatedAt(timestamp time.Time)

func (*BasicAccessData) SetExpiresIn

func (data *BasicAccessData) SetExpiresIn(seconds int32)

func (*BasicAccessData) SetRedirectUri

func (data *BasicAccessData) SetRedirectUri(uri string)

func (*BasicAccessData) SetRefreshToken

func (data *BasicAccessData) SetRefreshToken(token string)

func (*BasicAccessData) SetScope

func (data *BasicAccessData) SetScope(scope string)

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth defines the values required for basic authentication.

type BasicAuthorizeData

type BasicAuthorizeData struct {
	// Client information
	Client Client

	// Authorization code
	Code string

	// Token expiration in seconds
	ExpiresIn int32

	// Requested scope
	Scope string

	// Redirect Uri from request
	RedirectUri string

	// State data from request
	State string

	// Date created
	CreatedAt time.Time
}

BasicAuthorizeData is the default AuthorizeData type.

func (*BasicAuthorizeData) ExpiresAt

func (data *BasicAuthorizeData) ExpiresAt() time.Time

ExpiresAt returns this AuthorizeData's expiration timestamp.

func (*BasicAuthorizeData) GetClient

func (data *BasicAuthorizeData) GetClient() Client

func (*BasicAuthorizeData) GetCode

func (data *BasicAuthorizeData) GetCode() string

func (*BasicAuthorizeData) GetCreatedAt

func (data *BasicAuthorizeData) GetCreatedAt() time.Time

func (*BasicAuthorizeData) GetExpiresIn

func (data *BasicAuthorizeData) GetExpiresIn() int32

func (*BasicAuthorizeData) GetRedirectUri

func (data *BasicAuthorizeData) GetRedirectUri() string

func (*BasicAuthorizeData) GetScope

func (data *BasicAuthorizeData) GetScope() string

func (*BasicAuthorizeData) GetState

func (data *BasicAuthorizeData) GetState() string

func (*BasicAuthorizeData) IsExpired

func (data *BasicAuthorizeData) IsExpired() bool

IsExpired returns true if this AuthorizeData is expired, false otherwise.

func (*BasicAuthorizeData) SetClient

func (data *BasicAuthorizeData) SetClient(client Client)

func (*BasicAuthorizeData) SetCode

func (data *BasicAuthorizeData) SetCode(code string)

func (*BasicAuthorizeData) SetCreatedAt

func (data *BasicAuthorizeData) SetCreatedAt(timestamp time.Time)

func (*BasicAuthorizeData) SetExpiresIn

func (data *BasicAuthorizeData) SetExpiresIn(seconds int32)

func (*BasicAuthorizeData) SetRedirectUri

func (data *BasicAuthorizeData) SetRedirectUri(uri string)

func (*BasicAuthorizeData) SetScope

func (data *BasicAuthorizeData) SetScope(scope string)

func (*BasicAuthorizeData) SetState

func (data *BasicAuthorizeData) SetState(state string)

type BasicClient

type BasicClient struct {
	// Client id
	Id string

	// Client secrent
	Secret string

	// Base client uri
	RedirectUri string
}

BasicClient is the default client type.

func (*BasicClient) GetId

func (client *BasicClient) GetId() string

func (*BasicClient) GetRedirectUri

func (client *BasicClient) GetRedirectUri() string

func (*BasicClient) GetSecret

func (client *BasicClient) GetSecret() string

func (*BasicClient) SetId

func (client *BasicClient) SetId(id string)

func (*BasicClient) SetRedirectUri

func (client *BasicClient) SetRedirectUri(uri string)

func (*BasicClient) SetSecret

func (client *BasicClient) SetSecret(secret string)

type Client

type Client interface {
	GetId() string
	SetId(string)

	GetSecret() string
	SetSecret(string)

	GetRedirectUri() string
	SetRedirectUri(string)
}

Client is any struct type that has getters and setters for some required Client parameters.

type DefaultErrorId

type DefaultErrorId string

type DefaultErrors

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

Default errors and messages

func NewDefaultErrors

func NewDefaultErrors() *DefaultErrors

func (*DefaultErrors) Get

func (e *DefaultErrors) Get(id string) *HttpError

type HttpError

type HttpError struct {
	Status  int
	Message string
}

An HttpError is an error with a Status. In most cases, the Status field should be used as the response code of any http responses returning the error to a client.

func ValidateUri

func ValidateUri(baseUri string, redirectUri string) *HttpError

func (HttpError) Error

func (err HttpError) Error() string

type InfoRequest

type InfoRequest struct {
	Code       string
	AccessData AccessData
}

type Server

type Server struct {
	Config            *ServerConfig
	Storage           Storage
	AuthorizeTokenGen AuthorizeTokenGen
	AccessTokenGen    AccessTokenGen
}

OAuth2 server class

func NewServer

func NewServer(config *ServerConfig, storage Storage) *Server

Creates a new server instance

func (*Server) FinishAccessRequest

func (s *Server) FinishAccessRequest(params objx.Map, ar *AccessRequest, target AccessData) (response objx.Map, httpErr *HttpError)

func (*Server) FinishAuthorizeRequest

func (s *Server) FinishAuthorizeRequest(params objx.Map, ar *AuthorizeRequest, target interface{}) (redirect string, err *HttpError)

func (*Server) FinishInfoRequest

func (s *Server) FinishInfoRequest(r *http.Request, ir *InfoRequest) objx.Map

func (*Server) GetValidAccessData

func (s *Server) GetValidAccessData(token string) (AccessData, *HttpError)

GetValidAccessData takes a access token and a *Response, then tries to load an AccessData from storage and validate that data. It will return nil for the returned AccessData and an error if there are any problems locating or validating the requested data (i.e. if the AccessData's Client value returned from GetClient() is nil or has an empty GetRedirectUri() response), or the validated AccessData and nil for an error otherwise.

func (*Server) GetValidAuthData

func (s *Server) GetValidAuthData(code string) (AuthorizeData, *HttpError)

GetValidAuthData takes an authorization code and a *Response, then tries to load an AuthorizeData from storage and validate that data. It will return nil for the returned AuthorizeData and an error if there are any problems locating or validating the requested data (i.e. if the AuthorizeData's Client value returned from GetClient() is nil or has an empty GetRedirectUri() response), or the validated AuthorizeData and nil for an error otherwise.

func (*Server) GetValidClient

func (s *Server) GetValidClient(id string) (Client, *HttpError)

GetValidClient takes a client id and a *Response, then tries to load a client from storage and validate that client. It will return nil for the returned Client and a *HttpError if there are any problems locating or validating the requested client (i.e. if the client doesn't exist or has an empty GetRedirectUri() response), or the validated Client and nil for an error otherwise.

func (*Server) GetValidClientWithSecret

func (s *Server) GetValidClientWithSecret(id, secret string) (Client, *HttpError)

GetValidClientWithSecret takes a client id, secret, and a *Response, then returns the client if both GetValidClient returns a valid client and the passed in secret matches the client's secret.

func (*Server) GetValidRefresh

func (s *Server) GetValidRefresh(token string) (AccessData, *HttpError)

GetValidRefresh takes a refresh token and a *Response, then tries to load an AccessData from storage and validate that data. It will return nil for the returned AccessData and an error if there are any problems locating or validating the requested data (i.e. if the AccessData's Client value returned from GetClient() is nil or has an empty GetRedirectUri() response), or the validated AccessData and nil for an error otherwise.

func (*Server) HandleAccessRequest

func (s *Server) HandleAccessRequest(request *http.Request, params objx.Map) (*AccessRequest, *HttpError)

HandleAccessRequest takes a *http.Request and a map of input parameters, and returns a *AccessRequest representing the request for an access token and a *HttpError if any error is encountered.

func (*Server) HandleAuthorizeRequest

func (s *Server) HandleAuthorizeRequest(params objx.Map) (*AuthorizeRequest, *HttpError)

HandleAuthorizeRequest takes a *Response and an objx.Map of parameters, and returns a *AuthorizeRequest representing the request present in the *http.Request and parameters.

func (*Server) HandleInfoRequest

func (s *Server) HandleInfoRequest(r *http.Request) (*InfoRequest, *HttpError)

type ServerConfig

type ServerConfig struct {
	// Authorization token expiration in seconds (default 5 minutes)
	AuthorizationExpiration int32

	// Access token expiration in seconds (default 1 hour)
	AccessExpiration int32

	// Token type to return
	TokenType string

	// List of allowed authorize types (only CODE by default)
	AllowedAuthorizeTypes AllowedAuthorizeType

	// List of allowed access types (only AUTHORIZATION_CODE by default)
	AllowedAccessTypes AllowedAccessType

	// HTTP status code to return for errors - default 200
	// Only used if response was created from server
	ErrorStatusCode int

	// If true allows client secret also in params, else only in
	// Authorization header - default false
	AllowClientSecretInParams bool

	// If true allows access request using GET, else only POST - default false
	AllowGetAccessRequest bool
}

Server configuration

func NewServerConfig

func NewServerConfig() *ServerConfig

type Storage

type Storage interface {
	// Load client.
	GetClient(id string) (Client, error)

	// Save authorize data.
	SaveAuthorize(AuthorizeData) error

	// Load authorize data. Client information MUST be loaded together.
	// Optionally can return error if expired.
	LoadAuthorize(code string) (AuthorizeData, error)

	// Remove authorize data.
	RemoveAuthorize(code string) error

	// Save access data. If RefreshToken is not blank, must save in a way
	// that can be loaded using LoadRefresh.
	SaveAccess(AccessData) error

	// Load access data. Client information MUST be loaded together.
	// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
	// Optionally can return error if expired.
	LoadAccess(code string) (AccessData, error)

	// Remove access data.
	RemoveAccess(code string) error

	// Load refresh access data. Client information MUST be loaded together.
	// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
	// Optionally can return error if expired.
	LoadRefresh(code string) (AccessData, error)

	// Remove refresh data.
	RemoveRefresh(code string) error
}

Storage interface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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