authkit

package module
Version: v0.0.0-...-6ee20fc Latest Latest
Warning

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

Go to latest
Published: May 2, 2021 License: MIT Imports: 21 Imported by: 0

README

authkit

authkit is a small go toolkit for an Oauth2 explicit flow and is great for pure javascript apps which calls stateless REST services where the user must be authenticated. You don't have to store a session or any other credentials store in the backend of your servers. Simply create a login page, register this application with one of your favourite Oauth2 providers and let the user login and use your REST services. The services are full clusterable as long as every instance has the same private key associated to verify the JWT token.

You can embed this toolkit in your webapp and your browser and server will do the oauth2 explicit flow. If the user is successfully authenticated a JWT token and a user structure is returned to the browser. On the serverside your code will receive a AuthUser which contains the following fields:

// An AuthUser is a Uid and a Name. The backgroundurl
// and the thumbnailurl are optional an can be empty.
type AuthUser struct {
	Network       Provider   `json:"network"`
	ID            string     `json:"id"`
	EMail         string     `json:"email"`
	Name          string     `json:"name"`
	BackgroundURL string     `json:"backgroundurl"`
	ThumbnailURL  string     `json:"thumbnail"`
	Fields        Unparsed   `json:"fields"`
}

The Fields field contains the structure sent from the provider.

Your client can store the JWT token and embed this value to every call to one of your REST services. authkit also is a small middleware toolkit which intercepts the requests and parses the JWT token. Your handler functions will receive the authenticated user as an additional parameter.

autkit

Put something like this in your server code:

// register your OAUTH-apps with "<scheme>://<server>:<port>/authkit" and
// "<scheme>://<server>:<port>/authkit/redirect"
var kit = authkit.Must("/authkit") // <-- this name will be in the URL
...
kit.Add(authkit.Instance(
  authkit.Google, 
  os.Getenv("GOOGLE_CLIENTID"), 
  os.Getenv("GOOGLE_CLIENTSECRET")))
kit.RegisterDefault()
http.HandleFunc("/authed/", a.Handle(authed))
...
func authed(ac *authkit.AuthContext, w http.ResponseWriter, rq *http.Request) {
	log.Printf("user: %#v", ac.User)
	for k, v := range ac.Claims {
		log.Printf(" - vals[%s] = %s\n", k, v)
	}
}

and your client should embed the JS library:

<script src="/authkit/js"></script>

authkit.login('google').user(function (usr, tok) {
  ...
});

If you want to use some specific webframeworks or don't like the extended method signature, you can pull the context out of a normal web request:

func normal(w http.ResponseWriter, rq *http.Request) {
	ctx, err := kit.Context(rq)
	if err != nil {
		log.Printf("no valid auth context found: %s", err)
	} else {
		log.Printf("current authenticated user: %#v", ctx.User)
	}
}

Current supported providers:

  • Google
  • Github
  • Linkedin
  • Live (Windows)

Documentation

Overview

Package authkit is a small library to provide a 3-legged oauth explicit flow for stateless rest services. You need a webapp for the user which communicates with a server backend. This backend uses authkit to talk to the oauth providers and generates a JWT token. All of the rest services can use authkit or any other JWT library to parse the token. When using clustered services you should distribute your private key to all of your services to check the JWT signature.

Index

Constants

View Source
const (
	Facebook Provider = "facebook"
	Google            = "google"
	Github            = "github"
	Live              = "live"
	LinkedIn          = "linkedin"
)

some constants

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthContext

type AuthContext struct {
	User   AuthUser
	Claims Values
	// contains filtered or unexported fields
}

An AuthContext contains an authenticated user and additional claims

func (*AuthContext) Expire

func (ac *AuthContext) Expire(t time.Time) (string, error)

Expire generates a new token with the given time as the new expiration time. It is up to the caller to transport this new token to the client.

type AuthHandler

type AuthHandler func(ac *AuthContext, w http.ResponseWriter, rq *http.Request)

An AuthHandler is a callback function with the current authenticated user and claims. The claims are all values which are stored in the JWT token. You can put your own values with a specific TokenExtender function in the Authkit.

type AuthRegistration

type AuthRegistration struct {
	Network        Provider `json:"network"`
	ClientID       string   `json:"clientid"`
	ClientSecret   string   `json:"clientsecret"`
	Scopes         []string `json:"scopes"`
	AuthURL        string   `json:"authurl"`
	AccessType     string   `json:"access_type"`
	AccessTokenURL string   `json:"accesstokenurl"`
	UserinfoURLs   []string `json:"userinfo_urls"`
	UserinfoBase   string   `json:"userinfo_base"`
	PathEMail      string   `json:"pathemail"`
	PathID         string   `json:"pathid"`
	PathName       string   `json:"pathname"`
	PathPicture    string   `json:"pathpicture"`
	PathCover      string   `json:"pathcover"`
}

AuthRegistration describes a provider to authenticate against.

func FillDefaults

func FillDefaults(backend Provider, reg AuthRegistration) AuthRegistration

FillDefaults fills the given registration struct with the default values from the backend. The values are only overwritten if they are empty.

func GetRegistry

func GetRegistry(backend Provider) AuthRegistration

GetRegistry returns a registry description for the given backend or an empty registration block.

func Instance

func Instance(backend Provider, clientid, clientsecret string, scopes ...string) AuthRegistration

Instance returns a new registration provider with the given clientid and clientsecret.

type AuthUser

type AuthUser struct {
	Network       Provider `json:"network"`
	ID            string   `json:"id"`
	EMail         string   `json:"email"`
	Name          string   `json:"name"`
	BackgroundURL string   `json:"backgroundurl"`
	ThumbnailURL  string   `json:"thumbnail"`
	Fields        Unparsed `json:"fields"`
}

An AuthUser is a Uid and a Name. The backgroundurl and the thumbnailurl are optional an can be empty.

type Authkit

type Authkit struct {
	// The Finalizer will be called at the end of the authentication to
	// finalize the JWT token.
	TokenExtender Extender
	// contains filtered or unexported fields
}

An Authkit stores a map of providers which are identified by a networkname.

func Must

func Must(url string) *Authkit

Must returns a new kit or panics if it fails

func New

func New(url string) (*Authkit, error)

New returns a new Authkit with the given url as a prefix

func (*Authkit) Add

func (kit *Authkit) Add(r AuthRegistration)

Add will add the given registration to the map of providers. If there is already a provider with the same 'Network' name, the old one will be overwritten.

func (*Authkit) Context

func (kit *Authkit) Context(rq *http.Request) (*AuthContext, error)

Context returns the current authentication context from the given request.

func (*Authkit) DumpKey

func (kit *Authkit) DumpKey() string

DumpKey returns a string representation of the current RSA private key

func (*Authkit) Handle

func (kit *Authkit) Handle(h AuthHandler) http.HandlerFunc

Handle turns a AuthHandler to a normal HandlerFunc

func (*Authkit) Register

func (kit *Authkit) Register(mux *http.ServeMux)

Register the kit to the given mux.

func (*Authkit) RegisterDefault

func (kit *Authkit) RegisterDefault()

RegisterDefault registers the kit to the default http mux.

func (*Authkit) ServeHTTP

func (kit *Authkit) ServeHTTP(w http.ResponseWriter, rq *http.Request)

The authkit is a general http handler

func (*Authkit) UseKey

func (kit *Authkit) UseKey(r io.Reader) error

UseKey puts the PEM encoded key from the given reader to the authkit.

func (*Authkit) WithKeyfile

func (kit *Authkit) WithKeyfile(kf string) *Authkit

WithKeyfile loads the given private key and stores it in the Authkit. If the file cannot be loaded this function panics. If you need more control call 'UseKey' instead.

type Extender

type Extender func(AuthUser, Token) (time.Duration, Values, error)

Extender is a function which must return a expire duration for the JWT token. The function also can return a map of (string,string) pairs which will be embedded in the JWT token. If this function returns an error, the whole authentication fails.

func (Extender) Merge

func (tf Extender) Merge(f Extender) Extender

Merge merges two extender functions. The duration of the extender in the parameter list will be used. The values in the value map will be merged so that the values of the given extender will overwrite the others.

type Provider

type Provider string

A Provider is a name for a network provider.

type ProviderRegistry

type ProviderRegistry map[Provider]AuthRegistration

A ProviderRegistry contains all registerd providers.

type Token

type Token struct {
	AccessToken  string    `json:"access_token"`
	TokenType    string    `json:"token_type"`
	RefreshToken string    `json:"refresh_token"`
	Expiry       time.Time `json:"expiry"`
}

A Token is a response from a backend provider.

type Unparsed

type Unparsed map[string]interface{}

An Unparsed value is a raw map with the unparsed json contents.

type Values

type Values map[string]string

Values are additional values for the JWT token which can be filled by the application.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL