authn

package
v1.0.11 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2023 License: MIT, LGPL-3.0 Imports: 13 Imported by: 0

README

Keratin Authn Client

Keratin AuthN is an authentication service that keeps you in control of the experience without forcing you to be an expert in web security.

This library provides utilities to help integrate with a Go application. You may also need a client for your frontend, such as https://github.com /keratin/authn-js.

Godoc Gitter Build Status Go Report

Installation

go get github.com/SimifiniiCTO/simfiny-core-lib/third-party/authn

Example

package main

import (
  "fmt"
  sdk "github.com/SimifiniiCTO/simfiny-core-lib/third-party/authn"
)

var jwt1 = `<your test jwt here>`
var accountID = `<test ID>`

func main() {
  err := sdk.NewClient(sdk.Config{
    // The AUTHN_URL of your Keratin AuthN server. This will be used to verify tokens created by
    // AuthN, and will also be used for API calls unless PrivateBaseURL is also set.
    Issuer:         "https://issuer.example.com",

    // The domain of your application (no protocol). This domain should be listed in the APP_DOMAINS
    // of your Keratin AuthN server.
    Audience:       "application.example.com",

    // Credentials for AuthN's private endpoints. These will be used to execute admin actions using
    // the Client provided by this library.
    //
    // TIP: make them extra secure in production!
    Username:       "<Authn Username>",
    Password:       "<Authn Password>",

    // RECOMMENDED: Send private API calls to AuthN using private network routing. This can be
    // necessary if your environment has a firewall to limit public endpoints.
    PrivateBaseURL: "http://private.example.com",
  })
  fmt.Println(err)

  // SubjectFrom will return an AuthN account ID that you can use as to identify the user, if and
  // only if the token is valid.
  sub, err := sdk.SubjectFrom(jwt1)
  fmt.Println(sub)
  fmt.Println(err)

  // LockAccount will lock an AuthN account using the same ID that you saw in the user's JWT when
  // they signed up. That account will be unable to log in until it is unlocked.
  //
  // See the godocs for all actions that you can take on an account.
  err = sdk.LockAccount(accountID)
  fmt.Println(err)
}

Documentation

Index

Constants

View Source
const (
	// DefaultKeychainTTL is the default TTL for a key in keychain in minutes.
	DefaultKeychainTTL = 60
)

Variables

View Source
var ErrInvalidOptions = errors.New("invalid options for SubjectFrom")

ErrInvalidOptions is returned by SubjectFrom if invalid options are used.

View Source
var (
	// ErrNoKey is returned when no key is found in the keychain.
	ErrNoKey = errors.New("no keys found")
)

Functions

func Configure

func Configure(config Config, origin string) error

Configure initializes the default AuthN client with the given config. This is necessary to use lib.SubjectFrom without keeping a reference to your own AuthN client.

func SubjectFrom

func SubjectFrom(idToken string) (string, error)

SubjectFrom will use the the client configured by Configure to extract a subject from the given idToken.

Types

type Account

type Account struct {
	ID       int    `json:"id"`
	Username string `json:"username"`
	Locked   bool   `json:"locked"`
	Deleted  bool   `json:"deleted"`
}

Account is an AuthN user account.

type AuthService

type AuthService interface {
	// GetAccount Get a user account
	GetAccount(id string) (*Account, error)
	// Update Updates the username associated with a user account
	Update(id, username string) error
	// LockAccount Locks a user account
	LockAccount(id string) error
	// UnlockAccount Unlocks a user account
	UnlockAccount(id string) error
	// ArchiveAccount Archives a user account
	ArchiveAccount(id string) error
	// ImportAccount Creates a new user account
	ImportAccount(username, password string, locked bool) (int, error)
	// ExpirePassword Expires the password associated with a user account
	ExpirePassword(id string) error
	// LoginAccount Authenticates a user account
	LoginAccount(username, password string) (string, error)
	// SignupAccount Signs up a user account
	SignupAccount(username, password string) (string, error)
	// LogOutAccount Remove a session associated with a given user account
	LogOutAccount() error
	// RequestPasswordReset provides business logic to request to reset a given password
	RequestPasswordReset(username string) error
	// ResetPassword enables a new password change while logged out
	ResetPassword(password, token string) (string, error)
	// ChangePassword enables a client to change a given password while authenticated
	ChangePassword(newPassword, currentPassword string) (string, error)
}

AuthService exposes the interface contract the authentication service client adheres to.

type Claims

type Claims struct {
	// The time before which the JWT MUST NOT be accepted for processing.
	AuthTime *jwt.NumericDate `json:"auth_time"`
	jwt.Claims
}

Claims represents the claims in an Authn idToken.

type Client

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

Client provides JWT verification for ID tokens generated by the AuthN server. In the future it will also implement the server's private APIs (aka admin actions).

var DefaultClient *Client

DefaultClient can be initialized by Configure and used by SubjectFrom.

func New

func New(config Config, origin string, retryConfig *RetryConfig) (*Client, error)

New returns an initialized and configured Client.

func (*Client) ArchiveAccount

func (ac *Client) ArchiveAccount(id string) error

ArchiveAccount archives the account with the associated id.

func (*Client) ChangePassword

func (ac *Client) ChangePassword(neswPassword, oldPassword string) (string, error)

ChangePassword attempts to change a password while authenticated.

func (*Client) ClaimsFrom

func (ac *Client) ClaimsFrom(idToken string) (*jwt.Claims, error)

ClaimsFrom will return all verified claims inside the given idToken if and only if the token is a valid JWT that passes all verification requirements. If the JWT does not verify, the returned error will explain why. This is for debugging purposes.

func (*Client) ClaimsFromWithAudience

func (ac *Client) ClaimsFromWithAudience(idToken string, audience jwt.Audience) (*jwt.Claims, error)

ClaimsFromWithAudience works like ClaimsFrom but allows specifying a different JWT audience.

func (*Client) ExpirePassword

func (ac *Client) ExpirePassword(id string) error

ExpirePassword expires the password of the account with the associated id.

func (*Client) GetAccount

func (ac *Client) GetAccount(id string) (*Account, error)

GetAccount gets the account with the associated id.

func (*Client) ImportAccount

func (ac *Client) ImportAccount(username, password string, locked bool) (int, error)

ImportAccount imports an account with the provided information, returns the imported account id.

func (*Client) LockAccount

func (ac *Client) LockAccount(id string) error

LockAccount locks the account with the associated id.

func (*Client) LogOutAccount

func (ac *Client) LogOutAccount() error

LogOutAccount logs a user out of the systems by revoking all associated tokens to the account.

func (*Client) LoginAccount

func (ac *Client) LoginAccount(username, password string) (string, error)

LoginAccount attempts to log in the account with the input credentials and returns a jwt token.

func (*Client) RequestPasswordReset

func (ac *Client) RequestPasswordReset(username string) error

RequestPasswordReset initiates a password reset request.

func (*Client) ResetPassword

func (ac *Client) ResetPassword(password, token string) (string, error)

ResetPassword resets a password based on the provided token.

func (*Client) ServerStats

func (ac *Client) ServerStats() (*http.Response, error)

ServerStats gets the http response object from calling the server stats endpoint.

func (*Client) ServiceStats

func (ac *Client) ServiceStats() (*http.Response, error)

ServiceStats gets the http response object from calling the service stats endpoint.

func (*Client) SignupAccount

func (ac *Client) SignupAccount(username, password string) (string, error)

SignupAccount attempts to sign up the account with the input credentials and returns a jwt token.

func (*Client) SubjectFrom

func (ac *Client) SubjectFrom(idToken string) (string, error)

SubjectFrom will return the subject inside the given idToken if and only if the token is a valid JWT that passes all verification requirements. The returned value is the AuthN server's account ID and should be used as a unique foreign key in your users data.

If the JWT does not verify, the returned error will explain why. This is for debugging purposes.

func (*Client) SubjectFromWithAudience

func (ac *Client) SubjectFromWithAudience(idToken string, audience jwt.Audience) (string, error)

SubjectFromWithAudience works like SubjectFrom but allows specifying a different JWT audience.

func (*Client) UnlockAccount

func (ac *Client) UnlockAccount(id string) error

UnlockAccount unlocks the account with the associated id.

func (*Client) Update

func (ac *Client) Update(id, username string) error

Update updates the account with the associated id.

type Config

type Config struct {
	Issuer         string //the base url of the service handling authentication
	PrivateBaseURL string //overrides the base url for private endpoints
	Audience       string //the domain (host) of the main application
	Username       string //the http basic auth username for accessing private endpoints of the lib issuer
	Password       string //the http basic auth password for accessing private endpoints of the lib issuer
	KeychainTTL    int    //TTL for a key in keychain in minutes
}

Config is a configuration struct for Client.

type ErrorResponse

type ErrorResponse struct {
	StatusCode int          `json:"-"`
	URL        string       `json:"-"`
	Errors     []FieldError `json:"errors"`
}

ErrorResponse is returned together with 4xx and 5xx HTTP status codes and contains a list of error conditions encountered while processing an API request It implements the error interface.

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

Error implements the error interface.

func (*ErrorResponse) Field

func (e *ErrorResponse) Field(field string) (string, bool)

Field returns the error message for field if any.

func (*ErrorResponse) HasField

func (e *ErrorResponse) HasField(field string) bool

HasField returns true if field caused an error.

type FieldError

type FieldError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

FieldError is a returned for each field in an API request that does not match the expectations. Examples are MISSING, TAKEN, INSECURE, ...

func (FieldError) String

func (f FieldError) String() string

String returns a string representation of f and implements fmt.Stringer.

type IdResult

type IdResult struct {
	Id string `json:"id_token"`
}

IdResult is the result of a login request.

type JWKProvider

type JWKProvider interface {
	Key(kid string) ([]jose.JSONWebKey, error)
}

JWKProvider Provides a JSON Web Key from a Key ID Wanted to use function signature from go-jose.v2 but that would make us lose error information.

type JWTClaimsExtractor

type JWTClaimsExtractor interface {
	GetVerifiedClaims(idToken string) (*jwt.Claims, error)
}

JWTClaimsExtractor Extracts verified in-built claims from a jwt idToken.

func NewIDTokenVerifier

func NewIDTokenVerifier(issuer, audience string, keychain JWKProvider) (JWTClaimsExtractor, error)

NewIDTokenVerifier creates a new idTokenVerifier object by using keychain as the JWK provider Claims are verified against the values specified in config.

type LoginResponse

type LoginResponse struct {
	Result IdResult `json:"result"`
}

LoginResponse serves as the response to the login request.

type RetryConfig

type RetryConfig struct {
	MaxRetries       int
	MinRetryWaitTime time.Duration
	MaxRetryWaitTime time.Duration
	RequestTimeout   time.Duration
}

RetryConfig provides a mechanism by which clients can configure http retries parameters.

Jump to

Keyboard shortcuts

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