Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

auth

> 安全
Open source

Authenticator via oauth2, direct, email and telegram

1.3K stars0 likes0 views
WebsiteGitHub

About

Authenticator via oauth2, direct, email and telegram

auth - authentication via oauth2, direct and email

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.

  • Multiple oauth2 providers can be used at the same time
  • Special dev provider allows local testing and development
  • JWT stored in a secure cookie with XSRF protection. Cookies can be session-only
  • Minimal scopes with user name, id and picture (avatar) only
  • Direct authentication with user's provided credential checker
  • Verified authentication with user's provided sender (email, im, etc)
  • Custom oauth2 server and ability to use any third party provider
  • Integrated avatar proxy with an FS, boltdb and gridfs storage
  • Support of user-defined storage for avatars
  • Identicon for default avatars
  • Black list with user-defined validator
  • Multiple aud (audience) supported
  • Secure key with customizable SecretReader
  • Ability to store an extra information to token and retrieve on login
  • Pre-auth and post-auth hooks to handle custom use cases.
  • Middleware for easy integration into http routers
  • Wrappers to extract user info from the request
  • Role based access control

v1 vs v2 Differences

The v2 version of this library is now the actively developed version, and we recommend using it for new projects. Key differences include:

  • JWT library updated to use github.com/golang-jwt/jwt/v5 (from v3)
  • JWT token claims use modern structures from jwt/v5:
    • StandardClaims replaced with RegisteredClaims
    • Claims.ExpiresAt changed from int64 to *jwt.NumericDate
    • Claims.NotBefore changed from int64 to *jwt.NumericDate
    • Claims.IssuedAt changed from int64 to *jwt.NumericDate
    • ID field renamed from Id
    • Audience changed from string to []string
  • RefreshCache interface signatures updated to use strongly typed values:
    • Get(key string) (value token.Claims, ok bool)
    • Set(key string, value token.Claims)
  • Improved type safety for various interfaces and functions

To migrate from v1 to v2:

  1. Update import paths to use /v2 (e.g., github.com/go-pkgz/auth/v2)
  2. Update any custom code that accesses token fields to use the new structures
  3. If implementing RefreshCache interface, update method signatures

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:

  • Updating all auth package imports to use /v2
  • Modifying token handling code to work with the new JWT v5 structures:
    • Changing StandardClaims references to RegisteredClaims
    • Updating code accessing token expiration times to use *jwt.NumericDate
    • Converting string audience fields to use string arrays - it was a single string in the v3
  • Updating RefreshCache implementation to match the new interface
  • Adjusting tests to accommodate the new token structure
  • Fixing token claims validation and verification logic

The PR demonstrates how to handle migration for a production application with extensive auth usage.

Install

go get -u github.com/go-pkgz/auth/v2

Usage

Example with routegroup (stdlib-based router):

…

Example with chi router

…

Middleware

github.com/go-pkgz/auth/middleware provides ready-to-use middleware.

  • middleware.Auth - requires authenticated user
  • middleware.Admin - requires authenticated admin user
  • middleware.Trace - doesn't require authenticated user, but adds user info to request
  • middleware.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.

Details

Generally, adding support of auth includes a few relatively simple steps:

  1. Setup auth.Opts structure with all parameters. Each of them documented and most of parameters are optional and have sane defaults.
  2. Create the new auth.Service with provided options.
  3. Add all desirable authentication providers.
  4. Retrieve middleware and http handlers from auth.Service
  5. Wire auth and avatar handlers into http router as sub–routes.

API

For 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)

User info

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 name
  • ID - hash of user id
  • Picture - 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 address
  • Email - user's email
  • Attributes - 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.

Avatar proxy

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

  • On each login the proxy will retrieve user's picture and save it to AvatarStore
  • Local (proxied) link to avatar included in user's info (jwt token)
  • API for avatar removal provided as a part of AvatarStore
  • User can leverage one of the provided stores:
    • avatar.LocalFS - file system, each avatar in a separate file
    • avatar.BoltDB - single boltdb file (embedded KV store).
    • avatar.GridFS - external GridFS (mongo db).
  • In case of need custom implementations of other stores can be passed in and used by auth library. Each store has to implement avatar.Store interface.
  • All avatar-related setup done as a part of auth.Opts and needs:
    • AvatarStore - avatar store to use, i.e. avatar.NewLocalFS("/tmp/avatars") or more generic avatar.NewStore(uri)
      • file system uri - file:///tmp/location or just /tmp/location
      • boltdb - bolt://tmp/avatars.bdb
      • mongo - "mongodb://127.0.0.1:27017/test?ava_db=db1&ava_coll=coll1
    • AvatarRoutePath - 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.

Direct authentication

In addition to oauth2 providers auth.Service allows to use direct user-defined authentication. This is done by adding direct provider with auth.AddDirectProvider.

go
	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 request could be encoded as application/x-www-form-urlencoded or application/json:
    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 request with user credentials provided as query params, but be aware that the https query string is not secure:
    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.

Verified authentication

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.

go
    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 ID

Sender should be provided by end-user and implements a single function interface

go
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 session

The provider acts like any other, i.e. will be registered as /auth/email/login.

Confirmation token replay protection

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

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Goauthenticationcustom-oauth2gogolang

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category安全
PricingOpen source

> Related tools

O
OWASP ZAP
开源 Web 应用安全扫描器
O
owasp-wstg-tracker
Simple web app to track OWASP WSTG security testing progress
H
homebridge-mi-gateway-security
XiaoMi Gateway Security plugin for HomeBridge.