authjwt

package module
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2024 License: MIT Imports: 20 Imported by: 0

README

authjwt

This package is a GO (GOLANG) package that provides JWT authentication.

This package is used by github.com/paulfdunn/rest-app, see that project for example usage.

Key features:

  • Authentication is handled using JWT (JSON Web Tokens).
  • Authentication supports 2 user creation models: anyone can create a login, or only a registered user can create a new login. The later is the default in the example app.
  • Authentication supports 2 runtime models: You can include authjwt in your service, or you can use authjwt to create an auth service to be used by one or more independent services. In the later model, tokens are issues by the authentication service using a relatively short expiration interval, and client services can only validate that a token was valid when issued. Client services cannot verify the user hasn't used the authentication service to log out or invalidate all tokens. (Thus keeping a short JWTAuthExpirationInterval, and frequent refresh, is important.)
  • Authentication supports REGEX based validation/rules for passwords.
  • All authentication data and tokens are stored in a SQLITE database.
    • Passwords are hashed, then stored. The clear text password is not persisted.
  • Multiple tokens are allowed per user, allowing login/logout from different devices.
  • The provided wrappers log all DELETE/POST/PUT calls to an audit log.
  • Uses jwt.SigningMethodRS256, so the public key can be used to decode a token.

Security

Use only HTTPS to prevent tokens being stolen in-flight; I.E. public wi-fi with HTTP. Callers should not store the tokens. Use the token for the session only; the user can save their credentials via their browser, if they chose, to make logging in easier. Do also allow your users access to logout-all, as well as to the number of tokens available for their ID.

Usage

Applications only need call Init with a Config object, and optional http.ServeMux. If a mux is provided, the paths in the config object are wrapped in the authjwt handlers (thus enabling authentication) and registered. If no mux is provided in the Init call, applications must wrap their handlers using HandlerFuncAuthJWTWrapper.

Once initialized, authjwt handlers will respond to the specified paths to let callers: create/delete/update their authentication, login/logout (logout from the calling device)/logout-all (logout of any device), refresh (extend the time a token is valid), or get information about their authentication.

For detailed usage and example applications, see github.com/paulfdunn/rest-app. There are examples of both authentication embedded in a service, and running as an independent service.

Documentation

Overview

Package authjwt implements JWT authentication.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HandlerFuncAuthJWTWrapper

func HandlerFuncAuthJWTWrapper(hf func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request)

HandlerFuncAuthJWTWrapper is a basic wrapper that verifies the call is authenticated. Use this directly, or for additional verification of Authorizations, Role, etc., use this as an example. Note this wrapper also handles audit logging (logging for all DELETE/POST/PUT methods)

func HandlerFuncNoAuthWrapper

func HandlerFuncNoAuthWrapper(hf func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request)

HandlerFuncNoAuthWrapper is a basic wrapper that DOES NOT authenticate, but does handle audit logging (logging for all DELETE/POST/PUT methods)

func Init

func Init(configIn Config, mux *http.ServeMux)

Init initializes the package. createRequiresAuth == true requires auth creates to be from an already authenticated user. (Use for apps that require users be added by an admin.)

Types

type AuditWriter

type AuditWriter struct {
	http.ResponseWriter
	Message    string
	StatusCode int
}

AuditWriter is used to wrap the http.ResponseWriter passed to handlers in order to store information that is then written to the audit log as the handler exits. Applications using this package need to populate the Message as is done in these handlers in order for messages to show up in the audit log. Best practice is to only add logging information to the audit log once all validations are complete and the command is returning good status. Other information should be logged to an application log.

func (*AuditWriter) WriteHeader

func (aw *AuditWriter) WriteHeader(status int)

type Config

type Config struct {
	// AppName is used to populate the Issuer field of the Claims.
	AppName string
	// AuditLogName is the name of the logh logger for the audit log. Callers
	// must create their own logh loggers or output will go to STDOUT.
	AuditLogName string
	// DataSourcePath is the path to the SQLITE database used to persist auth and tokens.
	DataSourcePath string
	// CreateRequiresAuth - when true, requires an already authorized caller to create new
	// credentials. When false any caller can create their own auth.
	CreateRequiresAuth bool
	// JWTAuthRemoveInterval is the interval at which a GO routine runs, checks for expired
	// tokens, and invalidates all expired tokens. (A user can login from multiple devices
	// and can have more than one outstanding token.)
	JWTAuthRemoveInterval time.Duration
	// JWTAuthExpirationInterval is the duration for which a token is valid.
	JWTAuthExpirationInterval time.Duration
	// JWTPrivateKeyPath is the path to the private key used for signing the tokens.
	JWTPrivateKeyPath string
	// JWTPublicKeyPath is the path to the public key used for signing the tokens.
	JWTPublicKeyPath string
	// LogName is the name of the logh logger for general logging. Callers
	// must create their own logh loggers or output will go to STDOUT.
	LogName string
	// PasswordValidation is a slice of REGEX used for password validation. If nothing is
	// provided, defaultPasswordValidation is used.
	PasswordValidation []string
	// PathCreateOrUpdate is the final portion of the URL path for auth create or update.
	// If empty the default is used: /auth/createorupdate
	// Valid HTTP methods: http.MethodPost, http.MethodPut
	PathCreateOrUpdate string
	// PathDelete is the final portion of the URL path for delete. If empty the
	// default is used: /auth/delete
	// Valid HTTP methods: http.MethodDelete
	PathDelete string
	// PathInfo is the final portion of the URL path for info. If empty the
	// default is used: /auth/info
	// Valid HTTP methods: http.MethodGet
	PathInfo string
	// PathLogin is the final portion of the URL path for login. If empty the
	// default is used: /auth/login
	// Valid HTTP methods: http.MethodPut
	PathLogin string
	// PathLogout is the final portion of the URL path for logout. If empty the
	// default is used: /auth/logout
	// Valid HTTP methods: http.MethodDelete
	PathLogout string
	// PathLogoutAll is the final portion of the URL path for logout-all. If empty the
	// default is used: /auth/logout-all
	// Valid HTTP methods: http.MethodDelete
	PathLogoutAll string
	// PathRefresh is the final portion of the URL path for refresh. If empty the
	// default is used: /auth/refresh
	// Valid HTTP methods: http.MethodPost
	PathRefresh string
	// contains filtered or unexported fields
}

type Credential

type Credential struct {
	Email    *string
	Password *string
}

Credential is what is supplied by the HTTP request in order to authenticate.

func (*Credential) AuthCreate

func (cred *Credential) AuthCreate() error

AuthCreate creates or updates an ID/authentication pair to kvsAuth. The scope of the function is public to allow apps to create auths directly, without going through the ReST API.

type CustomClaims

type CustomClaims struct {
	jwt.StandardClaims
	Email   string
	TokenID string
}

CustomClaims are the Claims for the JWT token.

func Authenticated

func Authenticated(w http.ResponseWriter, r *http.Request) (*CustomClaims, error)

Authenticated checks the request for a valid token and will return the users CustomClaims, or an error is auth fails. The token is verified to still exist in kvsToken; meaning the user has not logged out with that token. On any error the header is written with the appropriate http.Status; callers should not write header status.

func AuthenticatedNoTokenInvalidation

func AuthenticatedNoTokenInvalidation(w http.ResponseWriter, r *http.Request) (*CustomClaims, error)

AuthenticatedNoTokenInvalidation checks the request for a valid token and will return the users CustomClaims, or an error is auth fails. The token is NOT verified to still exist in kvsToken; the token may have been invalidated but no error from this function means the token was valid at some point. This function should only be used by independent services that recieve tokens but don't have access to kvsToken. On any error the header is written with the appropriate http.Status; callers should not write header status.

type Info

type Info struct {
	OutstandingTokens int
}

Info is used to provide information back to the user.

Jump to

Keyboard shortcuts

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