Authenticator via oauth2, direct, email and telegram
This library provides "social login" with Github, Google, Facebook, Microsoft, Twitter, Yandex, Battle.net, Apple, Patreon, Discord and Telegram as well as custom auth providers and email verification.
dev provider allows local testing and developmentSecretReaderThe v2 version of this library is now the actively developed version, and we recommend using it for new projects. Key differences include:
github.com/golang-jwt/jwt/v5 (from v3)StandardClaims replaced with RegisteredClaimsClaims.ExpiresAt changed from int64 to *jwt.NumericDateClaims.NotBefore changed from int64 to *jwt.NumericDateClaims.IssuedAt changed from int64 to *jwt.NumericDateID field renamed from IdAudience changed from string to []stringGet(key string) (value token.Claims, ok bool)Set(key string, value token.Claims)To migrate from v1 to v2:
/v2 (e.g., github.com/go-pkgz/auth/v2)Complex Project Migration
For a real-world example of migrating a complex project from v1 to v2, see Remark42's migration PR. This migration included:
/v2StandardClaims references to RegisteredClaims*jwt.NumericDateThe PR demonstrates how to handle migration for a production application with extensive auth usage.
go get -u github.com/go-pkgz/auth/v2
Example with routegroup (stdlib-based router):
…Example with chi router
…github.com/go-pkgz/auth/middleware provides ready-to-use middleware.
middleware.Auth - requires authenticated usermiddleware.Admin - requires authenticated admin usermiddleware.Trace - doesn't require authenticated user, but adds user info to requestmiddleware.RBAC - requires authenticated user with passed role(s)Also, there is a special middleware middleware.UpdateUser for population and modifying UserInfo in every request. See "Customization" for more details.
Generally, adding support of auth includes a few relatively simple steps:
auth.Opts structure with all parameters. Each of them documented and most of parameters are optional and have sane defaults.auth.Service with provided options.auth.ServiceFor the example above authentication handlers wired as /auth and provides:
/auth//login?site=&from= - site_id used as aud claim for the token and can be processed by SecretReader to load/retrieve/define different secrets. redirect_url is the url to redirect after successful login. When Opts.AllowedRedirectHosts is set, only targets whose host matches Opts.URL or appears in the allowlist are honoured; others fall back to the user-info JSON response. With the default (nil) allowlist any non-empty from is honoured — see "Allowed redirect hosts" below for the opt-in details./avatar/ - returns the avatar (image). Links to those pictures added into user info automatically, for details see "Avatar proxy"/auth//logout and /auth/logout - invalidate "session" by removing JWT cookie/auth/list - gives a json list of active providers/auth/user - returns token.User (json)/auth/status - returns status of logged in user (json)Middleware populates token.User to request's context. It can be loaded with token.GetUserInfo(r *http.Request) (user User, err error) or token.MustGetUserInfo(r *http.Request) User functions.
token.User object includes all fields retrieved from oauth2 provider:
Name - user nameID - hash of user idPicture - full link to proxied avatar (see "Avatar proxy")It also has placeholders for fields application can populate with custom token.ClaimsUpdater (see "Customization")
IP - hash of user's IP addressEmail - user's emailAttributes - map of string:any-value. To simplify management of this map some setters and getters provided, for example users.StrAttr, user.SetBoolAttr and so on. See user.go for more details.Direct links to avatars won't survive any real-life usage if they linked from a public page. For example, page like this may have hundreds of avatars and, most likely, will trigger throttling on provider's side. To eliminate such restriction auth library provides an automatic proxy
AvatarStoreAvatarStoreauth library. Each store has to implement avatar.Store interface.auth.Opts and needs:AvatarStore - avatar store to use, i.e. avatar.NewLocalFS("/tmp/avatars") or more generic avatar.NewStore(uri)file:///tmp/location or just /tmp/locationbolt://tmp/avatars.bdb"mongodb://127.0.0.1:27017/test?ava_db=db1&ava_coll=coll1AvatarRoutePath - route prefix for direct links to proxied avatar. For example /api/v1/avatars will make full links like this - http://example.com/api/v1/avatars/1234567890123.image. The url will be stored in user's token and retrieved by middleware (see "User Info")AvatarResizeLimit - size (in pixels) used to resize the avatar. Pls note - resize happens once as a part of Put call, i.e. on login. 0 size (default) disables resizing.In addition to oauth2 providers auth.Service allows to use direct user-defined authentication. This is done by adding direct provider with auth.AddDirectProvider.
service.AddDirectProvider("local", provider.CredCheckerFunc(func(user, password string) (ok bool, err error) {
ok, err = checkUserSomehow(user, password)
return ok, err
}))Such provider acts like any other, i.e. will be registered as /auth/local/login.
The API for this provider supports both GET and POST requests:
POST /auth//login?session=[1|0]
body: application/x-www-form-urlencoded
user=&passwd=&aud=POST /auth//login?session=[1|0]
body: application/json
{
"user": "name",
"passwd": "xyz",
"aud": "bar",
}GET /auth//login?user=&passwd=&aud=&session=[1|0]note: password parameter doesn't have to be naked/real password and can be any kind of password hash prepared by caller.
note: session=1 makes the auth cookie session-only, i.e. dropped when the browser closes. sess is accepted as an alias for backward compatibility.
Another non-oauth2 provider allowing user-confirmed authentication, for example by email or slack or telegram. This is
done by adding confirmed provider with auth.AddVerifProvider.
msgTemplate := "Confirmation email, token: {{.Token}}"
service.AddVerifProvider("email", msgTemplate, sender)Message template may use the follow elements:
{{.Address}} - user address, for example email{{.User}} - user name{{.Token}} - confirmation token{{.Site}} - site IDSender should be provided by end-user and implements a single function interface
type Sender interface {
Send(address string, text string) error
}For convenience a functional wrapper SenderFunc provided. Email sender provided in provider/sender package and can be
used as Sender.
The API for this provider:
GET /auth//login?user=&address=&aud=&from= - send confirmation request to user. site is accepted as an alias for aud. When host validation is enabled via Opts.AllowedRedirectHosts, the from URL is subject to the same allowlist check described in "Allowed redirect hosts"; otherwise any non-empty value is honoured.GET /auth//login?token=&session=[1|0] - authorize with confirmation token, sess is accepted as an alias for sessionThe provider acts like any other, i.e. will be registered as /auth/email/login.
Confirmation tokens are one-shot: a token redeemed once cannot be redeemed again within its TTL. This stops anyone with read access to the email link (forwarded mail, mail-gateway logs, mailbox archive) from independently consuming it after the user has.
By default the library installs an in-memory store on first call to AddVerifProvider. This is correct for single-instance deployments.
Multi-instance deployments behind a load balancer MUST supply a shared backend. With the default in-memory store, replay protection works only on the instance that originally consumed the token; an attacker who hits any other instance can still re
No open issues yet, or sync has not completed.