Skip to content
go-pkgzPublic

Repository files navigation

auth - authentication via oauth2, direct and email

Build Status Coverage Status godoc

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 an HttpOnly cookie (Secure with SecureCookies) 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.

Version 1 gets security fixes where its dependencies allow. It still depends on github.com/golang-jwt/jwt v3, which has GO-2025-3553 (excessive memory allocation during header parsing), and no v3 release fixes it. v2 uses github.com/golang-jwt/jwt/v5 and is not affected, so v1 users should move to v2.

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. Tokens issued by the library still encode a single audience as a string, as v1 tokens do. Earlier v2 releases had token.NewService set jwt.MarshalSingleStringAsArray to false for the whole process; it now leaves the setting unchanged. With the golang-jwt default (true), tokens an application signs itself with jwt.ClaimStrings and direct JSON encoding of token.Claims encode a single audience as an array. An application can set the variable to false itself to keep its previous encoding
  • 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
  • Opts.ErrorHandler and middleware.ErrorHandlerFunc exist in v2 only; v1 always answers with the plain text "Unauthorized" (401) or "Access denied" (403)

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

func main() {
	// define options
	options := auth.Opts{
		SecretReader: token.SecretFunc(func(id string) (string, error) { // secret key for JWT
			return "secret", nil
		}),
		TokenDuration:  time.Minute * 5, // token expires in 5 minutes
		CookieDuration: time.Hour * 24,  // cookie expires 1 day after it was last issued and will enforce re-login
		Issuer:         "my-test-app",
		URL:            "http://127.0.0.1:8080",
		AvatarStore:    avatar.NewLocalFS("/tmp"),
	}

	// create auth service with providers
	service := auth.NewService(options)
	service.AddProvider("github", "<Client ID>", "<Client Secret>")   // add github provider
	service.AddProvider("facebook", "<Client ID>", "<Client Secret>") // add facebook provider

	// retrieve auth middleware
	m := service.Middleware()

	// setup http server
	router := routegroup.New(http.NewServeMux())
	router.HandleFunc("GET /open", openRouteHandler) // open api
	router.Group().Route(func(r *routegroup.Bundle) {
		r.Use(m.Auth)
		r.HandleFunc("GET /private", protectedRouteHandler) // protected api
	})

	// setup auth routes
	authRoutes, avaRoutes := service.Handlers()
	router.Handle("/auth/", authRoutes) // add auth handlers
	router.Handle("/avatar/", avaRoutes) // add avatar handler

	log.Fatal(http.ListenAndServe(":8080", router))
}
Example with chi router
func main() {
	// define options
	options := auth.Opts{
		SecretReader: token.SecretFunc(func(id string) (string, error) { // secret key for JWT
			return "secret", nil
		}),
		TokenDuration:  time.Minute * 5, // token expires in 5 minutes
		CookieDuration: time.Hour * 24,  // cookie expires 1 day after it was last issued and will enforce re-login
		Issuer:         "my-test-app",
		URL:            "http://127.0.0.1:8080",
		AvatarStore:    avatar.NewLocalFS("/tmp"),
	}

	// create auth service with providers
	service := auth.NewService(options)
	service.AddProvider("github", "<Client ID>", "<Client Secret>")   // add github provider
	service.AddProvider("facebook", "<Client ID>", "<Client Secret>") // add facebook provider

	// retrieve auth middleware
	m := service.Middleware()

	// setup http server
	router := chi.NewRouter()
	router.Get("/open", openRouteHandler)                      // open api
	router.With(m.Auth).Get("/private", protectedRouteHandler) // protected api

	// setup auth routes
	authRoutes, avaRoutes := service.Handlers()
	router.Mount("/auth", authRoutes)  // add auth handlers
	router.Mount("/avatar", avaRoutes) // add avatar handler

	log.Fatal(http.ListenAndServe(":8080", router))
}

Middleware

service.Middleware() returns a middleware.Authenticator (github.com/go-pkgz/auth/v2/middleware) with ready-to-use middleware methods:

  • Auth - requires authenticated user
  • AdminOnly - requires authenticated admin user
  • Trace - doesn't require authenticated user, but adds user info to request
  • RBAC(roles...) - requires authenticated user with passed role(s)

Also, there is a special middleware method 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. The middleware accepts a token when its provider is registered on this service, matched by the provider name signed into the token or by the part of the user id before the first _ (the whole id when it has none). A service registering only bitbucket therefore also accepts tokens of a provider named bitbucket_dev. A service that only verifies tokens issued elsewhere must register the same provider names.
  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/<provider>/login?site=<site_id>&from=<redirect_url> - site_id used as aud claim for the token and can be processed by SecretReader to load/retrieve/define different secrets. The oauth2, oauth1 and Apple providers also accept aud=<site_id> in place of site, and noava=1, which drops the provider's picture, so a configured avatar proxy generates an identicon instead. 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/<avatar_id> - returns the avatar (image). Links to those pictures added into user info automatically, for details see "Avatar proxy"
  • /auth/<provider>/logout and /auth/logout - invalidate "session" by removing the JWT and XSRF cookies. Both are served by the provider added first, whatever provider name the path carries; with Opts.AuthRoutePath set, that name has to be a registered provider
  • /auth/list - gives a json list of active providers
  • /auth/user - returns token.User (json) of a request the Auth middleware accepts, which includes the Validator and the check that the user's provider is still registered; 401 otherwise
  • /auth/status - returns status of logged in user (json), by the same checks as /auth/user

By default the handler takes the route from the end of the path, whatever is in front of it: /auth/x/github/login is the github login and /auth/github/status is /auth/status. A middleware in front of the handler that goes by the path, such as a rate limiter, then sees several paths for one endpoint. Set Opts.AuthRoutePath to the path the handler is mounted at, as the handler sees it, for example /auth, and the handler answers only list, logout, user and status, and <provider>/<action> such as github/login or github/callback, right under that path. Any other path gets 404, including one with an escape such as %2F or %64 in the provider or action element, and a provider name that is not registered 400. The path is compared as written, so keep its segments to ASCII letters, digits and -._~: a segment with other characters can get 404, as clients escape them differently, and one that has to be escaped in a URL, such as café, always does. With AuthRoutePath: "/" the path has to reach the handler with its leading slash: http.StripPrefix("/auth", h) keeps it, while http.StripPrefix("/auth/", h) turns /auth/list into list and every route gets 404. A middleware in front that removes a prefix has to trim RawPath along with Path, as http.StripPrefix does; otherwise a request whose removed part carries a character such as ( or ! unescaped gets 404.

/auth/user and /auth/status report the identity Auth would accept, so a token from the cookie needs the X-XSRF-TOKEN header (Opts.XSRFHeaderKey) carrying the value of the XSRF-TOKEN cookie, and basic credentials accepted by AdminPasswd or BasicAuthChecker count as well. With such an identity they answer the token.User JSON and {"status":"logged in","user":"<name>"}; otherwise /auth/user answers 401 {"error":"unauthorized"} and /auth/status answers {"status":"not logged in"}. The logout applies the same XSRF rule when the provider added first is an oauth2, oauth1 or Apple provider: without a valid token it answers 403 {"error":"logout not allowed"} and keeps the cookies.

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 - user id; the built-in providers other than dev set it to <provider>_<hash of the user id>, the form the linking flow below relies on
  • Picture - full link to proxied avatar (see "Avatar proxy"); without an AvatarStore, the provider's own picture URL, or empty for Telegram, whose picture URL carries the bot token
  • Audience - the token's aud, filled in by token.Service.Get, which the middleware and /auth/user use; Parse leaves it empty, and the login response does not carry it

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 user.StrAttr, user.SetBoolAttr and so on. See user.go for more details.
  • Role - user's role, set with SetRole; RBAC compares it with the allowed roles case-insensitively

In JSON (the token, /auth/user and the login responses) the keys are name, id, picture, aud, ip, email, attrs and role.

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. Pictures that fail to load, exceed 10 MiB or 16 megapixels, or are not PNG, JPEG, GIF or WebP are replaced by the identicon
  • For OAuth2 providers the proxy sends the user's access token with the picture request only when the picture is on the scheme, host and port of the provider's user info URL, as with the Microsoft Graph photo; a picture on any other host, including one reached by a redirect, is fetched without it
  • 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). It is optional: nil disables the avatar proxy, keeps the provider's picture URL in Picture (Telegram leaves it empty), and the avatar route answers 404. avatar.NoOp stores nothing and leaves Picture pointing at an empty avatar path.
      • 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; mongodb+srv:// works too. Without ava_db and ava_coll the database is test and the collection avatars_fs
    • 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/b3daa77b4c04a9551b8781d03191fe098f325e67.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.
    • AvatarIdenticonSize - size (in pixels) of the identicon generated for a user without a picture, 300 by default; values from 5 to 4096 are accepted, others give 300. Browsers blur the block edges when they don't map to whole device pixels. At device pixel ratio 2, generating it at twice the displayed size gives a 1:1 pixel mapping; at ratio 1 the browser halves it, and whether the edges stay aligned depends on the size: 48 for a 24px avatar does, 64 for a 32px one doesn't. A positive AvatarResizeLimit below it still scales the identicon down. Like resizing, it applies on login, so stored identicons keep their size until the user logs in again.

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.

	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/<name>/login?session=[1|0]
    body: application/x-www-form-urlencoded
    user=<user>&passwd=<password>&aud=<site_id>
    
    POST /auth/<name>/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/<name>/login?user=<user>&passwd=<password>&aud=<site_id>&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.

The login answers 200 with the user JSON and sets the auth cookies, 400 when the request body cannot be parsed, 403 for wrong credentials, and 500 when the checker returns an error. The user id is <name>_<sha1(user)>, where <name> is the provider name and the hash is taken of the user name exactly as sent, so names differing only in case give different ids. To build the id from something else, register the provider with AddDirectProviderWithUserIDFunc (see Linking an anonymous user after login).

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.

    msgTemplate := `<p>Confirm your login: <a href="{{.URL}}/auth/email/login?token={{.LinkToken}}">log in</a></p>`
	service.AddVerifProvider("email", msgTemplate, sender)

The template receives the tokens, not a link, so the confirmation link, <Opts.URL>/auth/<name>/login?token=<token>, is written into the template itself, as above. A link made with {{.LinkToken}} leaves {{.Token}} valid, so the message can also show it for pasting.

Message template may use the following elements:

  • {{.Address}} - user address, for example email
  • {{.User}} - user name
  • {{.Token}} - confirmation token
  • {{.LinkToken}} - a second confirmation token for the same sign-in, meant for a link in the message. Both tokens are accepted by the login endpoint and each works once on its own, so using one leaves the other valid until it expires. The link token carries provider.VerifLinkTokenState as its handshake state, which lets an application serving the link refuse any other token
  • {{.Site}} - site ID
  • {{.URL}} - the service URL from Opts.URL, without a trailing slash

The template is an html/template, meant for HTML mail (set ContentType: "text/html" for the email sender below): every value is HTML-escaped, so in a plain-text message O'Brien arrives as O&#39;Brien. The template's User and Address values are stripped of line breaks and surrounding spaces and cut to 128 bytes; the tokens and the Sender get the values as sent. An empty template selects a built-in plain one with the user, the address, the site and the token.

Sender 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. A Sender that also implements provider.ContextSender (SendContext(ctx context.Context, address, text string) error), as the email sender does, gets the request context, so the delivery ends when the request does.

The API for this provider:

  • GET /auth/<name>/login?user=<user>&address=<address>&aud=<site_id>&from=<url> - 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. It answers {"user":"<user>","address":"<address>"} once the message is sent. The confirmation token is valid for 30 minutes; this is fixed.
  • GET /auth/<name>/login?token=<conf.token>&session=[1|0] - authorize with confirmation token, sess is accepted as an alias for session. It answers the user JSON, or redirects with 303 to from when one was given and is allowed.

The library checks only that user and address are not empty (400 otherwise) and that the address neither contains :: nor starts with : (400 invalid address). The first call needs no authentication, so anyone can make the service send a message with their own user text to any address, as often as they like. The application, or its Sender, must validate the address and rate-limit this route.

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

Only a signed handshake token that carries this provider's name is accepted for login. Session tokens, confirmations issued by another verify provider, and handshake tokens an application mints without this provider's name are rejected, even though they are signed with the same secret.

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. The protection is per token: a message whose template carries both {{.Token}} and {{.LinkToken}} lets a reader of the message sign in once more with whichever token the user did not use, until it expires. A template that needs the full guarantee carries only one of them.

This holds for providers added with AddVerifProvider. A provider.VerifyHandler constructed directly and registered with AddCustomHandler needs ConfirmationStore set; without it, its tokens can be replayed until they expire.

By default the library installs an in-memory store on first call to AddVerifProvider. This is correct for single-instance deployments, except that a restart forgets redeemed tokens, so a token redeemed before the restart can be redeemed again until it expires; a persistent Opts.VerifConfirmationStore covers restarts.

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 replay within the TTL. This is silent: the request succeeds and the auth flow completes normally, with no log indicating the protection was bypassed. Plug in Redis or any shared KV by setting Opts.VerifConfirmationStore to a value implementing provider.VerifConfirmationStore:

type VerifConfirmationStore interface {
    // MarkUsed records key as consumed and returns alreadyUsed=true if it was
    // already recorded. err signals a backend failure -- callers fail-closed
    // (reject the redemption) on non-nil err to avoid replay during outages.
    MarkUsed(key string, ttl time.Duration) (alreadyUsed bool, err error)
}

The store key is the SHA-256 of the token's signed header and payload, without the signature segment, so tokens need no extra id claim and the wire format is unchanged. The signature is left out because the same signature can be spelled in several ways that all verify, such as with a line break inserted, and each spelling would otherwise get a key of its own and sign in again. Consumption is final: a transient downstream failure after the mark burns the token; the user must request a new confirmation email rather than retry the same link.

Email-as-identity caveat

The verify provider returns a local user id of the form <provider>_<sha1(address)>. The address is hashed exactly as given, so user@example.com, User@Example.COM and user@example.com are three different users; normalise the address before the request (trim spaces, lower-case the domain), or map ids on the application side. The confirmation round-trip proves current control of the address at the moment of login; it does not prove stable+unique identity over time. The owner of an address can change without the address changing:

  • Employer offboarding — alice@example-corp.com returns to the company when Alice leaves and may be reassigned to a new employee.
  • Lapsed free-mail accounts — providers reclaim and recycle inactive mailboxes; the next person who registers the same handle inherits any service that keys on the address.
  • Domain recycling — when a personal domain is not renewed and is re-registered, the new owner can receive mail for every local part it ever had.

This is inherent to email-as-identity, not specific to this library — the verify flow has no upstream identifier (such as an OIDC sub) it could fall back on. Any application that keys its own records directly on the returned id will treat the new owner of an address as the original user.

Integrators that need stable identity should:

  • Map the verified address to a server-side immutable user id (e.g., a users table primary key) at first successful verify, and key application records, ACLs, and audit logs on that internal id rather than on the value returned by the provider.
  • Treat a verified address whose internal id is missing as a new account, not as a reactivation of an old one.
  • For higher-stakes systems, consider re-verification policies (re-prove address control after long inactivity) and reuse-detection signals before granting access to historical data.

If your threat model accepts that whoever currently controls an address gets the corresponding account (e.g. low-stakes commenting), no extra handling is required — but the property should be a deliberate choice, not an inherited default.

Email

For email notify provider, please use github.com/go-pkgz/auth/v2/provider/sender package:

	sndr := sender.NewEmailClient(sender.EmailParams{
		Host:               "email.hostname",
		Port:               587,
		HELOHost:           "mail.example.com", // optional, greeting hostname, defaults to localhost
		SMTPUserName:       "username",
		SMTPPassword:       "pass",
		StartTLS:           true,
		InsecureSkipVerify: false,
		From:               "notify@email.hostname",
		Subject:            "subject",
		ContentType:        "text/html",
		Charset:            "UTF-8",
	}, logger.Std)
	authenticator.AddVerifProvider("email", "template goes here", sndr)

EmailParams also has TLS (connect over TLS from the start), LoginAuth (LOGIN in place of PLAIN authentication, for servers that offer only LOGIN, e.g. Office 365 while the tenant allows basic SMTP authentication) and TimeOut (connection timeout). logger.Std comes from github.com/go-pkgz/auth/v2/logger. That documentation describes the options of the underlying email library; only the EmailParams fields reach it.

Telegram

Telegram provider allows your users to log in with Telegram account. First, you will need to create your bot. Contact @BotFather and follow his instructions to create your own bot (call it, for example, "My site auth bot")

Next initialize TelegramHandler with following parameters:

  • ProviderName - Any unique name to distinguish between providers
  • SuccessMsg - Message sent to user on successful authentication
  • ErrorMsg - Message sent on errors (e.g. login request expired)
  • Telegram - Telegram API implementation. Use provider.NewTelegramAPI with following arguments
    1. The secret token bot father gave you
    2. An http.Client for accessing Telegram API's
  • ChatIDAttribute - optional. The user ID stays the hashed telegram_... value; when this key is set, a fresh login also stores the user's raw Telegram chat ID as a string attribute under it (read with user.StrAttr(key)), so the app can message the user through the bot. Leave it empty unless the app needs the raw ID: the attribute goes into the JWT and the /auth/user and login responses. Users with tokens issued before the key was set get the attribute on their next login.

For a proxy in front of the Telegram API, use provider.NewTelegramAPIWithBaseURL(token, client, baseURL) in place of provider.NewTelegramAPI; it returns an error for a base URL that is not an absolute http or https URL. An empty base URL, or one made only of slashes, selects the public Telegram API.

token := os.Getenv("TELEGRAM_TOKEN")

telegram := provider.TelegramHandler{
	ProviderName: "telegram",
	ErrorMsg:     "❌ Invalid auth request. Please try clicking link again.",
	SuccessMsg:   "✅ You have successfully authenticated!",
	Telegram:     provider.NewTelegramAPI(token, http.DefaultClient),

	L:            logger.Std,
	TokenService: service.TokenService(),
	AvatarSaver:  service.AvatarProxy(),
}

After that run provider and register its handlers:

// Run Telegram provider in the background
go func() {
	err := telegram.Run(context.Background())
	if err != nil {
		log.Fatalf("[PANIC] failed to start telegram: %v", err)
	}
}()

// Register Telegram provider
service.AddCustomHandler(&telegram)

Run must be running before the first login, otherwise the login route answers 500 failed to process login request. An application that receives the bot's updates itself, for example through a webhook, calls ProcessUpdate instead, and the first call has to happen before the first login. ProcessUpdate takes updates in the shape getUpdates returns, {"result": [<update>, ...]}, so a single update from a webhook has to be wrapped in that result array; a bare update is accepted and ignored. The two exclude each other: ProcessUpdate returns an error while Run is running. Pending login requests live in the memory of the process, so the provider works on a single instance: the login call and the check have to reach the instance that holds the request and receives the updates.

Avatar handling

Telegram's file API requires the bot token in the URL path (https://api.telegram.org/file/bot<TOKEN>/...), so the URL is a bearer credential and must never reach the JWT, the user JSON, or any debug log. The provider fetches the avatar bytes server-side and stores them via AvatarSaver, returning a clean local proxy URL.

This requires AvatarSaver to support direct content saving. avatar.Proxy (the default returned by service.AvatarProxy()) does -- no extra setup needed. Custom AvatarSaver implementations that don't implement PutContent(userID string, content io.Reader) (string, error) will see an empty User.Picture for Telegram logins, and the avatar proxy will fall back to identicon. To preserve avatars with a custom saver, implement that method alongside Put.

Behaviour change for custom AvatarSaver: before v1.25.3 and v2.1.3, custom savers received the raw Telegram file URL (which included the bot token) via Put. Since those versions they no longer do, because that URL is a bearer credential. Implementations that relied on receiving and refetching that URL must now implement PutContent to keep saving Telegram avatars, or accept that Telegram users get identicons.

Now all your users have to do is click one of the following links and press start tg://resolve?domain=<botname>&start=<token> or https://t.me/<botname>/?start=<token>

Use the following routes to interact with provider:

  1. /auth/<providerName>/login - Obtain auth token. Returns JSON object with bot (bot username) and token (token itself) fields. The login request lives 10 minutes, and Run polls Telegram for updates every 5 seconds.

  2. /auth/<providerName>/login?token=<token>&site=<site_id> - Check if auth request has been confirmed (i.e. user pressed start). site sets the token's audience; aud is not read here. Sets the auth cookie, which is always persistent (session is ignored), and returns user info on success, errors with 404 otherwise.

  3. /auth/<providerName>/logout - Invalidate user session.

Custom oauth2

This provider brings two extra functions:

  1. Adds ability to use any third-party oauth2 providers in addition to the list of directly supported. Included example demonstrates how to do it for bitbucket. In order to add a new oauth2 provider following input is required:

    • Name - a path-safe name made of letters, digits, -, ., _ and ~; any other name is skipped with an [ERROR] log line and never shows in /auth/list. Avoid the names from list of supported providers, unless the custom provider replaces the built-in registration of that name, as in Google user email. It is possible to register more than one client for one given oauth2 provider (for example using different names bitbucket_dev and bitbucket_prod). Nothing rejects a name registered twice: both registrations are kept and the first one serves the routes
    • Client - ID and secret of client
    • Endpoint - auth URL and token URL. This information could be obtained from auth2 provider page
    • InfoURL - oauth2 provider API method to read information of logged in user. This method could be found in documentation of oauth2 provider (e.g. for bitbucket https://developer.atlassian.com/bitbucket/api/2/reference/resource/user)
    • MapUserFn - function to convert the response from InfoURL to token.User (s. example below). It must return an empty ID when the response has no user id: the callback then answers 503 and issues no session. Check the id before hashing it, because a prefix plus token.HashID of an empty value is not an empty ID and maps every such login to the same user. Hash an id the user chooses, such as a login name, with plain sha1 as below: token.HashID returns a value of 40 hex characters unchanged, so a user whose login spells the hash of another user's login would get that user's id
    • Scopes - minimal needed scope to read user information. Client should be authorized to these scopes
    • BearerTokenHookFn - optional, called after a successful login with the provider name, the mapped user and the provider's OAuth2 token; it is the way to keep that token for later API calls
    • AvatarSaver - optional, saves the user's picture for this provider in place of the service's avatar proxy. The callback hands the saver a client that sends the user's access token only with requests to the scheme, host and port of InfoURL, and the avatar proxy fetches the picture URL from the user info with it; a picture on any other host is fetched without the token. When users of the provider can set that URL, pass a saver that fetches the picture with a client of its own, for example one that refuses private addresses, and stores it through Service.AvatarProxy(). A host with non-ASCII characters never gets the token, so when the picture needs it, write both InfoURL and the picture URL with the host in its ASCII (xn--) form
    c := auth.Client{
    	Cid:     os.Getenv("AEXMPL_BITBUCKET_CID"),
    	Csecret: os.Getenv("AEXMPL_BITBUCKET_CSEC"),
    }
    
    service.AddCustomProvider("bitbucket", c, provider.CustomHandlerOpt{
    	Endpoint: oauth2.Endpoint{
    		AuthURL:  "https://bitbucket.org/site/oauth2/authorize",
    		TokenURL: "https://bitbucket.org/site/oauth2/access_token",
    	},
    	InfoURL: "https://api.bitbucket.org/2.0/user/",
    	MapUserFn: func(data provider.UserData, _ []byte) token.User {
    		username := data.Value("username")
    		if username == "" {
    			return token.User{} // no id in the response, the login is refused
    		}
    		userInfo := token.User{
    			ID:   "bitbucket_" + fmt.Sprintf("%x", sha1.Sum([]byte(username))),
    			Name: data.Value("nickname"),
    		}
    		return userInfo
    	},
    	Scopes: []string{"account"},
    })

    Behaviour change for custom providers: before v1.30.1 and v2.6.1, the client handed to the avatar saver sent the user's access token with every request to any address. Since those versions it sends the token only to the scheme, host and port of InfoURL. A picture on another origin that needs the token now gets an identicon from the default avatar proxy, and a custom AvatarSaver that returns that fetch error fails the login with 500. The client also has a five-second timeout per fetch attempt.

    Behaviour change for custom providers: up to v1.30.1 and v2.6.1, the user info request could follow a redirect to another origin and sent the access token on each followed hop. Since the releases after those versions it refuses a redirect off the scheme, host and port of InfoURL, and the login fails with 503. An http:// InfoURL that redirects to https:// on the same host is one such case: write it with https://. When the user info of a host with non-ASCII characters answers with a redirect, write the host in its ASCII (xn--) form in InfoURL and in any absolute redirect target on that host.

  2. Adds local oauth2 server user can fully customize. It uses github.com/go-oauth2/oauth2/v4 library and example shows how to initialize the server (initGoauth2Srv in the example) and set up a provider (the NewCustomServer call in main there).

    • to start local oauth2 server following options are used:
      • URL - url of oauth2 server with port, required
      • L - logger, required: Run logs before it starts listening, so a nil logger panics
      • WithLoginPage - optional flag to show the default login page, which asks for a user name and a password and passes both, as the username and password form values, to the UserAuthorizationHandler; the library itself requires only a non-empty username
      • LoginPageHandler - optional function to handle login request. When set, it is shown in place of the default login page, with or without WithLoginPage
    • the go-oauth2 server needs a UserAuthorizationHandler (srv.SetUserAuthorizationHandler) in every case; without a login page, /authorize goes straight to it and the user is never asked for a name. The user id it returns is used as it is, with no provider prefix, so it can collide with ids of other providers; prefix it in the handler, as the example does with custom123_admin
       sopts := provider.CustomServerOpt{
       	URL:           "http://127.0.0.1:9096",
       	L:             logger.Std,
       	WithLoginPage: true,
       }
       prov := provider.NewCustomServer(srv, sopts)
      
       // Start server
       go prov.Run(context.Background())
    • to register handler for local oauth2 following option are required:
      • Name - a path-safe name (letters, digits, -, ., _, ~) other than the names from list of supported providers; registering a name twice keeps the first registration
      • Client - ID and secret of client
      • HandlerOpt - handler options of custom oauth provider
       service.AddCustomProvider("custom123", auth.Client{Cid: "cid", Csecret: "csecret"}, prov.HandlerOpt)

Self-implemented auth handler

Additionally it is possible to implement own auth handler. It may be useful if auth provider does not conform to oauth standard. Self-implemented handler has to implement provider.Provider interface.

// customHandler implements provider.Provider interface
c := customHandler{}

// add customHandler to stack of auth handlers
service.AddCustomHandler(c)

Only paths ending in /login or /callback reach the handler, and only with GET or POST: other paths get 404 and other methods 405. Paths ending in /logout reach it only when it is the provider added first, since that provider serves every logout path. Every response of an auth route carries Content-Security-Policy: default-src 'none'; sandbox; frame-ancestors 'none', which blocks a handler that renders an HTML page; such a handler sets its own Content-Security-Policy header with w.Header().Set before writing, relaxing only the directives it needs.

Customization

There are several ways to adjust functionality of the library:

  1. SecretReader - interface with a single method Get(aud string) (string, error) to return the secret used for JWT signing and verification. Per-site secrets need Opts.AudSecrets: true; without it the reader is called with "ignore" when a token is verified, so it must return one secret for every site.
  2. ClaimsUpdater - interface with Update(claims Claims) Claims method. This is the primary way to alter a token at login time and add any attributes, set ip, email, admin status, roles and so on. Update is also called for the handshake and confirmation tokens, where claims.User is nil, so check it before use.
  3. Validator - interface with Validate(token string, claims Claims) bool method. This is post-token hook and will be called on each request wrapped with Auth middleware. This will be the place for special logic to reject some tokens or users. When the middleware refreshes an expired token, Validate is called on the claims as sent and again on the refreshed claims, which ClaimsUpdater has seen, with the token string as sent both times.
  4. UserUpdater - interface with Update(claims token.User) token.User method. This method will be called on each request wrapped with UpdateUser middleware. This will be the place for special logic modify User Info in request context. Example of usage.

All of the interfaces above have corresponding Func adapters - SecretFunc, ClaimsUpdFunc, ValidatorFunc and UserUpdFunc.

Additionally, ErrorHandlerFunc type is available in the middleware package for custom error handling on authentication failures:

options := auth.Opts{
    // ... other options ...
    ErrorHandler: middleware.ErrorHandlerFunc(func(w http.ResponseWriter, r *http.Request, code int, err error) {
        // return JSON error for API routes
        if strings.HasPrefix(r.URL.Path, "/api/") {
            w.Header().Set("Content-Type", "application/json")
            w.WriteHeader(code)
            json.NewEncoder(w).Encode(map[string]string{"error": "authentication required"})
            return
        }
        // redirect to login page for web routes
        http.Redirect(w, r, "/login", http.StatusFound)
    }),
}

By default (when ErrorHandler is nil), the middleware returns "Unauthorized" (401) or "Access denied" (403) text responses.

Implementing black list logic or some other filters

Restricting some users or some tokens is two step process:

  • ClaimsUpdater sets an attribute, like blocked (or allowed)
  • Validator checks the attribute and returns true/false

The process can be simplified by doing all checks directly in Validator, but depends on particular case such solution can be too expensive because Validator runs on each request as a part of auth middleware. In contrast, ClaimsUpdater called on token creation/refresh only.

A block set by ClaimsUpdater applies from the next refresh of the user's token: the middleware passes the refreshed claims to the Validator before it writes the new cookies, so the request that carries the expired cookie token gets no user (Auth refuses it with 401, or with what Opts.ErrorHandler answers, and Trace serves it anonymously) and its cookies are cleared. That is at most one token lifetime after the block, see Token lifetime. With Opts.RefreshCache, claims refreshed before the block are served from the cache for the same expired token until they expire or the cache drops them, whichever comes first, which keeps the same bound.

Linking an anonymous user after login

An app that lets users start anonymously (a direct provider, see Direct authentication) may want to move what they created to the account they log in with later. The library keeps no users, so the move is the app's job, and it must not happen automatically right after login: the email confirmation link and the Telegram token work from any browser, so an attacker can send his own confirmation link to a user who is in the middle of linking, that browser gets logged into the attacker's account, and an automatic merge would move the anonymous data there.

A flow that moves the data only after the user confirms the account, implemented and tested in v2/linking_example_test.go. How much the confirmation protects depends on the provider, see the end of this section.

  1. Make anonymous ids unguessable. With AddDirectProvider the id is a hash of the name, so anyone typing the same name gets the same id. Use AddDirectProviderWithUserIDFunc and add a random part:

    service.AddDirectProviderWithUserIDFunc("anonymous",
        provider.CredCheckerFunc(func(string, string) (bool, error) { return true, nil }), // any name, no password
        func(user string, _ *http.Request) string { return user + "::" + rand.Text() })  // crypto/rand
  2. Before redirecting to /auth/<provider>/login, call your own endpoint with POST, behind Middleware().Auth and with the XSRF header (Opts.XSRFHeaderKey, X-XSRF-TOKEN by default). It checks that the current user is anonymous, stores a pending record server-side (a random nonce, the anonymous id, the provider the user is about to log in with, for email the address they are about to confirm, an expiration) and sets the nonce in an HttpOnly, SameSite=Lax cookie, Secure when Opts.SecureCookies is set. Take Secure from Opts.SecureCookies like the JWT cookie does, not from r.TLS, which is nil behind a TLS-terminating proxy: for a link without an address, whoever reads the nonce can log into his own account on that provider and confirm. An app framed by another site sets and clears the nonce cookie with Opts.SameSiteCookie and Opts.PartitionedCookies like the JWT cookie, otherwise confirm never gets the nonce back; this covers the logins that happen inside the frame (direct, Telegram, email), not oauth popups, and the XSRF header check stays on. The record must outlive the login it waits for: the email confirmation token is valid for 30 minutes after it is sent, so a link with an address lives that long plus time to confirm. Call start again right before every letter request, resends included: the user is still anonymous then, and the address binding keeps an earlier letter working. A link without an address can keep a short window, since its nonce alone is enough to move the data; a login slower than that leaves the data with the anonymous id. Take the record's expiration and the cookie's MaxAge from one value. Don't read the anonymous token inside the login flow itself: the oauth providers replace the JWT cookie with a handshake token at the start of the login. Reject a start for email without the address.

  3. After the login, if the request carries the nonce cookie and the pending record is still alive, check the current user. Refuse a user who is still anonymous: the move would append the data to the same user and then delete it. Refuse a user of another provider than the one stored, and for email any id other than "<verify provider name>_" followed by the hex sha1 of the address, fmt.Sprintf("%x", sha1.Sum([]byte(address))), with the name passed to AddVerifProvider; keep it in one constant, so the check cannot drift from the registration. The example tells the provider by the <provider>_<hash> form of the user id, which the built-in oauth, Apple, Telegram, direct and verify providers set, and compares the whole part before the last _, since a provider name may contain _ itself. The dev provider, NewCustomServer with its default mapper, a custom MapUserFn and AddCustomHandler can return ids without it, and an Opts.ClaimsUpd can rewrite the id, so with those the app needs its own way to tell the provider. Then show Move your anonymous data to <account>? and remember the exact user id shown. Only a confirmation POST (with the same XSRF header) moves the data. The POST carries the user id the screen showed, and the move happens only when it equals both the current user id and the last id shown, so an old screen cannot confirm after the browser was logged into another account. Move the data and delete the pending record in one transaction, so the move cannot run twice.

Only an email login can be bound to a known identity. The display name proves nothing (for email it comes from the user query parameter), and for Telegram, the oauth providers and a direct provider with a password the app cannot know the user id in advance, while the name and avatar can be copied from the victim. An attacker who gets the user's browser to open his own login link for the same provider passes every check above, so for those providers the move rests on the user recognizing the account on the confirmation screen. If that is not enough, offer linking only through email.

The endpoints of steps 2 and 3 must reject a token passed in the query parameter named by Opts.JWTQuery (token by default) or in the header named by Opts.JWTHeaderKey (X-JWT by default). An option left unset stays empty in your Opts, so fall back to the default name. The middleware accepts those before the cookie and does not check the XSRF header for them. The flow relies on that XSRF check, so it does not work with Opts.DisableXSRF or with POST in Opts.XSRFIgnoreMethods.

Multi-tenant services and support for different audiences

For complex systems a single authenticator may serve multiple distinct subsystems or multiple set of independent users. For example some SaaS offerings may need to provide different authentications for different customers and prevent use of tokens/cookies made by another customer.

Such functionality can be implemented in 3 different ways:

  • Different instances of auth.Service each one with different secret. Doing this way will ensure the highest level of isolation and cookies/tokens won't be even parsable across the instances. Practically such architecture can be too complicated and not always possible.
  • Handling "allowed audience" as a part of ClaimsUpdater and Validator chain. I.e. ClaimsUpdater sets a claim indicating expected audience code/id and Validator making sure it matches. This way a single auth.Service could handle multiple groups of auth tokens and reject some based on the audience.
  • Using the standard JWT aud claim. This method conceptually very similar to the previous one, but done by library internally and consumer don't need to define special ClaimsUpdater and Validator logic.

In order to allow aud support, set Opts.AudienceReader to a reader returning the allowed audiences:

opts := auth.Opts{
    AudienceReader: token.AudienceFunc(func() ([]string, error) {
        return []string{"site1", "site2"}, nil
    }),
    // ...
}

A non-nil reader enables the check on token creation (a token for an alien aud is not issued) and on every read of a token, Auth middleware included; a reader returning an empty list rejects all tokens. The token's first aud is compared with the list case-insensitively. The list is one allowlist for the whole service, so a site1 token passes on site2 routes too; a route that serves one tenant has to compare User.Audience with the tenant the request names.

Allowed redirect hosts

The from query parameter accepted by oauth2/oauth1/apple/verify login flows tells the server where to send the user after a successful auth handshake. The value is signed into the handshake JWT, so it can't be tampered with mid-flow — but a caller can put any URL into the initial login link. Without restriction this becomes a phishing vector: an attacker crafts a login link that bounces the victim through legitimate OAuth and then to an attacker-controlled landing page.

Default behaviour is permissive (Opts.AllowedRedirectHosts is nil): any non-empty from value is honoured. This preserves the behaviour of versions before the redirect validator existed, so a dependency bump never silently breaks an existing deployment. Hardening is opt-in.

To enable host validation, set Opts.AllowedRedirectHosts to anything implementing the token.AllowedHosts interface:

type AllowedHosts interface {
    Get() ([]string, error)
}

The token.AllowedHostsFunc adapter wraps an ordinary function, mirroring the token.AudienceFunc pattern:

opts := auth.Opts{
    URL: "https://app.example.com",
    AllowedRedirectHosts: token.AllowedHostsFunc(func() ([]string, error) {
        return []string{"admin.example.com", "billing.example.com"}, nil
    }),
    // ...
}

Once the policy is on:

  • The host of Opts.URL is always permitted implicitly (single-host deployments need no list entries — pass func() ([]string, error) { return nil, nil } to enable the policy with same-host-only semantics).
  • Values returned by Get() are appended to that. Subdomain wildcards are not supported — list each host explicitly.
  • Hostname comparison is port-insensitive: https://app.example.com and https://app.example.com:443 are treated as the same host, and a hostname without a port, the host of Opts.URL included even when Opts.URL names a port, accepts any port, https://app.example.com:8443 among them. An entry with a port, such as billing.example.com:8443, matches only that port.
  • Relative paths and unparseable URLs are rejected, and so are schemes other than http and https.
  • An error returned by Get() rejects a redirect to any host other than that of Opts.URL.
  • Rejected redirects are logged at [WARN] level with only the host portion of the URL (paths and query strings are stripped to avoid logging attacker-supplied data).

Dev provider

Working with oauth2 providers can be a pain, especially during development phase. A special, development-only provider dev can make it less painful. This one can be registered directly, i.e. service.AddProvider("dev", "", "") or service.AddDevProvider(host, port) and should be activated like this:

	// runs dev oauth2 server on :8084 by default
	go func() {
		devAuthServer, err := service.DevAuth()
		if err != nil {
			log.Fatal(err)
		}
		devAuthServer.Run(context.Background())
	}()

It will run fake oauth2 "server" on port :8084 and user could login with any user name. See example for more details.

The dev server sends the browser back to Opts.URL + /auth/dev/callback, whatever redirect_uri it receives, so the auth handlers must be mounted at /auth to use the dev provider. Open the application on the host Opts.URL names: localhost and 127.0.0.1 are different hosts to the browser, the login sets the handshake cookie on the host the page was opened on, and a callback arriving on the other one fails with 500 failed to get token (the log says token cookie was not presented). The dev provider's user id is the bare user name, without the <provider>_ prefix of the other providers.

By default, Dev provider doesn't return email claim from /user endpoint, to match behaviour of other providers which only request minimal scopes. However sometimes it is useful to have email included into user info. This can be done by configuring devAuthServer.GetEmailFn function:

	go func() {
		devAuthServer, err := service.DevAuth()
		if err != nil {
			log.Fatal(err)
		}
		devAuthServer.GetEmailFn = func(username string) string {
			return username + "@example.com"
		}
		devAuthServer.Run(context.Background())
	}()

Warning: this is not the real oauth2 server but just a small fake thing for development and testing only. Don't use dev provider with any production code.

Listen address

The dev OAuth server and the embedded CustomServer helper bind to 127.0.0.1 by default so the dev login UI is not silently exposed to the LAN, Docker network siblings, kubernetes pods on the same node, etc.

Dev provider

The dev provider has a separate Host field. It is the address the dev server listens on, and also the address the browser and the application use to reach it: the host of the authorise, token and user-info URLs and of the dev avatar link. The OAuth callback URL is taken from Opts.URL and is independent. To bind to all interfaces (e.g. when the auth process runs inside a container and needs to be reachable from the host) pass Host explicitly; the login then sends the browser to http://0.0.0.0:8084/login/oauth/authorize, the same coupling CustomServer has below:

// dev provider -- listen on all interfaces, callback URL stays whatever you set in Opts.URL
service.AddDevProvider("0.0.0.0", 8084)
CustomServer

CustomServer is the awkward case: CustomServerOpt.URL is used both as the bind source and as the advertised OAuth endpoint (it appears verbatim in AuthURL, TokenURL and InfoURL returned to clients). There is no separate bind setting today, so URL: "http://0.0.0.0:9096" is only appropriate when every consumer of those advertised endpoints is fine with 0.0.0.0 as a hostname -- which is essentially never the case in practice.

Recommended approaches:

  • Single host, no proxy -- leave URL: "http://localhost:9096" (or your real hostname). The default loopback bind matches the advertised host and everything works.
  • Behind a reverse proxy: not supported until a separate bind option exists -- Run listens on the host and port of URL, so until a separate bind option exists URL must name an address of the auth host itself, and a public address the proxy serves cannot be used there. When it cannot listen there (a public address the host does not have, or a URL without a port), Run returns at once and leaves only a log line. It also serves plain HTTP for an https:// URL while advertising https endpoints.
  • Direct LAN exposure with a sensible advertised URL -- set URL to a real hostname or LAN IP that resolves on every consumer (e.g. http://oauth.lan.example:9096); the bind extracts the host and listens there. Avoid embedding 0.0.0.0 in URL unless you have already accepted the consequence that clients will see 0.0.0.0 in the advertised metadata.

A future change is likely to add a separate bind option (CustomServerOpt.BindAddr or similar) so the bind and the advertised URL can diverge cleanly; until then, the bind follows URL.

Token lifetime

Opts.TokenDuration is the lifetime of a JWT the library issues through token.Service.Set (logins and refreshes) without an explicit expiry, 15 minutes by default. A token signed directly with TokenService().Token gets no expiry unless ExpiresAt is set, and v2 accepts such a token from the header or the query without limit; a Telegram login sets an explicit 30-minute expiry on its token, whatever TokenDuration is. Opts.CookieDuration is the lifetime of the cookie that carries the token, 31 days by default. Reissuing a persistent cookie on a refresh starts its full CookieDuration again, so CookieDuration limits idle time, not the age of a session. A token read from the cookie that has expired is refreshed on the next request while the cookie lives; a token from the header or the query is not refreshed. Opts.RefreshCache keeps refreshed claims keyed by the expired token, so a request carrying an expired token that was already refreshed takes the claims from the cache instead of refreshing it again; requests that arrive before the first refresh is cached each refresh. A request served from the cache gets its own copy of the cached claims and no new cookies, the Validator checks that copy again, and claims it refuses are not cached. Cached claims that have expired are not served: the token is refreshed again, and the new claims replace the entry once the Validator accepts them.

Other ways to authenticate

In addition to the primary method (i.e. JWT cookie with XSRF header) there are three more ways to authenticate:

  1. Send JWT header as X-JWT (the name is set by Opts.JWTHeaderKey). This shouldn't be used for web application, however can be helpful for service-to-service authentication.
  2. Send JWT token as query parameter, i.e. /something?token=<jwt> (the name is set by Opts.JWTQuery)
  3. Basic access authentication, for more details see below Basic authentication.

When a request carries more than one token, the query parameter is used first, then the header, then the cookie. Tokens from the header or the query are not XSRF-checked, and they are rejected once expired, while an expired cookie token is refreshed.

Basic authentication

In some cases the middleware.Authenticator allow use Basic access authentication, which transmits credentials as user-id/password pairs, encoded using Base64 (RFC 7617). When basic authentication used, client doesn't get auth token in response. It's auth type expect credentials in a header Authorization at every client request. It can be helpful, if client side not support cookie/token store (e.g. embedded device or custom apps). This mode disabled by default and will be enabled with options.

The auth package has two options of basic authentication:

  • simple basic auth will be enabled if Opts.AdminPasswd defined. This will allow access with basic auth admin:<Opts.AdminPasswd> with user admin. Such method can be used for automation scripts. A wrong admin password is not an error: the request goes on to the JWT check.
  • basic auth with custom checker function, which allow adding user data from store to context of request. It will be enabled if Opts.BasicAuthChecker defined. When BasicAuthChecker defined then Opts.AdminPasswd option will be ignore. A request with an Authorization: Basic header is then decided by the checker alone, so a wrong password gives 401 even when the request also carries a valid JWT cookie.

Users authenticated with basic auth skip the Validator, the provider check and the XSRF check.

options := auth.Opts{
   //...
   AdminPasswd:    "admin_secret_password", // will ignore if BasicAuthChecker defined
   BasicAuthChecker: func(user, passwd string) (bool, token.User, error) {
      if user == "basic_user" && passwd == "123456" {
           return true, token.User{Name: user, Role: "test_r"}, nil
      }
      return false, token.User{}, errors.New("basic auth credentials check failed")
   },
   //...
}

Logging

By default, this library doesn't print anything to stdout/stderr (the exceptions are the BoltDB avatar store and avatar.Migrate, which write a few messages to the standard log package whatever logger is set), however user can pass a logger implementing logger.L interface with a single method Logf(format string, args ...interface{}). Functional adapter for this interface included as logger.Func. There are two predefined implementations in the logger package - NoOp (prints nothing, default) and Std wrapping log.Printf from stdlib.

Register oauth2 providers

Authentication handled by external providers. You should setup oauth2 for all (or some) of them to allow users to authenticate. It is not mandatory to have all of them, but at least one should be correctly configured.

AddProvider and AddProviderWithUserAttributes accept these names, in any letter case: github, google, facebook, yandex, battlenet, microsoft, twitter, twitter_v2 (v2 only), patreon, discord and dev. Any other name registers nothing and logs an [ERROR] line. Apple, Telegram and custom providers are registered with their own methods: AddAppleProvider, AddCustomHandler and AddCustomProvider.

Every oauth2 login through the shared oauth2 handler, which serves the built-in oauth2 providers except Apple and every AddCustomProvider registration, uses PKCE (RFC 7636) with the S256 method: the login sends a code challenge, and the callback sends the matching verifier, kept in the handshake token, to the token endpoint. Servers without PKCE support ignore both, so no configuration is needed.

The oauth2, oauth1 and Apple callbacks read the handshake token only from the JWT cookie set by the login step. A handshake token passed in the JWT query parameter or header (token and X-JWT by default) is ignored on the callback, so the callback requires the handshake cookie from the login step. Login handlers give the handshake a 30-minute expiry, and the callback rejects a handshake whose expiry has passed, so a user who leaves the provider's consent page open longer has to start the login again. A handshake without an expiry is still accepted.

The callback from a provider on another site is a cross-site navigation, so Opts.SameSiteCookie decides whether the browser sends the handshake cookie with it. http.SameSiteStrictMode breaks every provider on another site, because the browser drops the handshake cookie on a cross-site callback; a provider on the same site, such as the dev server on the application's host, still works. Apple's form_post callback is a cross-site POST and needs http.SameSiteNoneMode with SecureCookies; Lax or the browser default can drop the cookie there, and the callback then fails with 500 failed to get token.

Google Auth Provider

  1. Create a new project: https://console.developers.google.com/project
  2. Choose the new project from the top right project dropdown (only if another project is selected)
  3. In the project Dashboard center pane, choose "API Manager"
  4. In the left Nav pane, choose "Credentials"
  5. In the center pane, choose the "OAuth consent screen" tab.
  • Select "External" and click "Create"
  • Fill in "App name" and select User support email
  • Upload a logo, if you want to
  • In the App Domain section:
    • Application home page - your site URL, e.g., https://mysite.com
    • Application privacy policy link - your site's privacy policy, e.g. https://mysite.com/privacy.html (please check that it works)
    • Terms of service - leave empty
  • Authorized domains - your site domain, e.g., mysite.com
  • Developer contact information - add your email, and then click Save and continue
  • On the Scopes tab, just click Save and continue
  • On the Test users, add your email, then click Save and continue
  • Before going to the next step, set the app to "Production" and send it to verification
  1. In the center pane, choose the "Credentials" tab
    • Open the "Create credentials" drop-down
    • Choose "OAuth client ID"
    • Choose "Web application"
    • Application Name is freeform; choose something appropriate, like "Comments on mysite.com"
    • Authorized JavaScript Origins should be your domain, e.g., https://remark42.mysite.com
    • Authorized redirect URIs is the location of OAuth2/callback constructed as domain + /auth/google/callback, e.g., https://remark42.mysite.com/auth/google/callback
    • Click "Create"
  2. Take note of the Client ID and Client Secret

instructions for google oauth2 setup borrowed from oauth2_proxy

Google user email

The built-in Google provider requests only the userinfo.profile scope, and Google includes email in the user info response only when the email scope was granted. The token therefore has no email, and mapping email with AddProviderWithUserAttributes gives an empty value. The minimal scope is deliberate, see #37.

To get the email, register Google as a custom provider in place of service.AddProvider("google", ...). Under the name google the registered callback URI stays /auth/google/callback, and the user id is computed the same way as by the built-in provider, so existing users keep their ids. google.Endpoint comes from golang.org/x/oauth2/google.

c := auth.Client{Cid: os.Getenv("GOOGLE_CID"), Csecret: os.Getenv("GOOGLE_CSEC")}
service.AddCustomProvider("google", c, provider.CustomHandlerOpt{
	Endpoint: google.Endpoint,
	InfoURL:  "https://www.googleapis.com/oauth2/v3/userinfo",
	Scopes: []string{
		"https://www.googleapis.com/auth/userinfo.profile",
		"https://www.googleapis.com/auth/userinfo.email",
	},
	MapUserFn: func(data provider.UserData, _ []byte) token.User {
		sub := data.Value("sub")
		if sub == "" {
			return token.User{} // no id in the response, the login is refused
		}
		u := token.User{
			ID:      "google_" + token.HashID(sha1.New(), sub),
			Name:    data.Value("name"),
			Picture: data.Value("picture"),
		}
		if u.Name == "" {
			u.Name = "noname_" + u.ID[8:12]
		}
		if data.Value("email_verified") == "true" {
			u.Email = data.Value("email")
		}
		return u
	},
})

The example sets Email only for an address Google reports as verified. Read the email-as-identity caveat before keying application records on it.

Microsoft Auth Provider

  1. Register a new application using the Azure portal.
  2. Under "Supported account types" select "Accounts in any organizational directory (Any Microsoft Entra directory - Multitenant) and personal Microsoft accounts"
  3. Under "Authentication/Platform configurations/Web" enter the correct url constructed as domain + /auth/microsoft/callback. i.e. https://example.mysite.com/auth/microsoft/callback
  4. In "Overview" take note of the Application (client) ID
  5. Select "Certificates & secrets" and click on "+ New Client Secret".

Microsoft avatars are available only through the avatar proxy (Opts.AvatarStore): the picture URL the provider returns, https://graph.microsoft.com/beta/me/photo/$value, needs the user's token, which the proxy has at login and a browser does not.

By default, the Microsoft provider uses the common tenant endpoint, which requires an application accepting both work or school accounts and personal Microsoft accounts. That corresponds to signInAudience: AzureADandPersonalMicrosoftAccount, which can be checked and changed under "Manifest" for an application that already exists. An application restricted to a single account type is rejected at that endpoint, for instance with AADSTS50194 when it is not registered as multi-tenant.

For single-tenant Entra ID (Azure AD) applications, or for an application limited to personal Microsoft accounts (consumers), use AddMicrosoftProvider to specify the tenant:

service.AddMicrosoftProvider("<Client ID>", "<Client Secret>", "<Tenant ID>")

The tenant value can be a tenant ID (GUID), domain name, or one of the well-known values: common, organizations, consumers. A value containing /, ?, #, a space, a tab, a line break or .. is not a valid tenant: the provider uses common instead and logs a warning.

GitHub Auth Provider

  1. Create a new "OAuth App": https://github.com/settings/developers
  2. Fill "Application Name" and "Homepage URL" for your site
  3. Under "Authorization callback URL" enter the correct url constructed as domain + /auth/github/callback. ie https://example.mysite.com/auth/github/callback
  4. Take note of the Client ID and Client Secret
Username-as-identity caveat

By default the GitHub provider derives the local user id from the account login, as github_<sha1(login)>. GitHub releases a username as soon as the account is renamed or deleted, and anyone can claim it afterwards. An application that keys its own records on the returned id will treat the next holder of a released username as the original user. This is the same property described in the email-as-identity caveat above, with one difference: GitHub returns an immutable numeric account id in the same response, so the provider can key on that instead.

To do so, register the provider with AddGithubProviderWithNumericID:

service.AddGithubProviderWithNumericID("<Client ID>", "<Client Secret>")

To combine it with UserAttributes, set GithubNumericID when building provider.Params directly and register the result with service.AddCustomHandler(provider.NewGithub(p)). That handler is registered as-is, so every field the service would normally supply has to be filled in by hand: URL, JwtService: service.TokenService(), AvatarSaver: service.AvatarProxy(), L, and AllowedRedirectHosts set to the same value passed in Opts. Leaving AllowedRedirectHosts nil turns off redirect host validation for that provider, so a service that sets it in Opts must repeat it here.

The numeric derivation is best-effort: if the /user response carries no usable numeric id, the provider keeps the login-derived id and logs a warning rather than failing the login.

This is off by default because it changes the id of every existing GitHub user. On a running deployment the switch is not transparent: comments, roles, blocks and any other records stored under the old id stop matching, and the old ids cannot be translated offline, because a login cannot be recovered from its hash. Turn it on for a new deployment, or migrate the stored ids yourself first. The recommendation in the email-as-identity caveat applies here too, and avoids the problem entirely: map the provider id to an internal immutable id of your own at first login, and key application records on that.

Facebook Auth Provider

  1. From https://developers.facebook.com select "My Apps" / "Add a new App"
  2. Set "Display Name" and "Contact email"
  3. Choose "Facebook Login" and then "Web"
  4. Set "Site URL" to your domain, ex: https://example.mysite.com
  5. Under "Facebook login" / "Settings" fill "Valid OAuth redirect URIs" with your callback url constructed as domain + /auth/facebook/callback
  6. Select "App Review" and turn public flag on. This step may ask you to provide a link to your privacy policy.

Apple Auth Provider

To configure this provider, a user requires an Apple developer account (without it setting up a sign in with Apple is impossible). Sign in with Apple lets users log in to your app using their two-factor authentication Apple ID.

Follow to next steps for configuring on the Apple side:

  1. Log in to the developer account.
  2. If you don't have an App ID yet, create one. Later on, you'll need TeamID, which is an "App ID Prefix" value.
  3. Enable the "Sign in with Apple" capability for your App ID in the Certificates, Identifiers & Profiles section.
  4. Create Service ID and bind with App ID from the previous step. Apple will display the description field value to end-users on sign-in. You'll need that service Identifier as a ClientID later on.
  5. Configure "Sign in with Apple" for created Service ID. Add domain where you will use that auth on to "Domains and subdomains", and add https://<your domain>/auth/apple/callback to "Return URLs". Apple accepts only https and no localhost.
  6. Register a New Key (private key) for the "Sign in with Apple" feature and download it. Write down the Key ID. This key will be used to create JWT Client Secret.
  7. Add your domain name and sender email in the Certificates, Identifiers & Profiles >> More section as a new Email Source. This is needed only to send mail to users through Apple's private relay, which this library never does.

After completing the previous steps, you can proceed with configuring the Apple auth provider. Here are the parameters for AppleConfig:

  • ClientID (required) - Service ID (or App ID) which is used for Sign with Apple
  • TeamID (required) - Identifier a developer account (use as prefix for all App ID)
  • KeyID (required) - Identifier a generated key for Sign with Apple
  • ResponseMode - Response Mode, please see documentation for reference, default is form_post. It is also the only value accepted: the provider requests the name scope, which Apple allows with form_post only, so AddAppleProvider returns an error for any other value
    // apple config parameters
	appleCfg := provider.AppleConfig{
		TeamID:   os.Getenv("AEXMPL_APPLE_TID"), // developer account identifier
		ClientID: os.Getenv("AEXMPL_APPLE_CID"), // Service ID (or App ID)
		KeyID:    os.Getenv("AEXMPL_APPLE_KEYID"), // private key identifier
	}

Then add an Apple provider that accepts the following parameters:

  • appleConfig (provider.AppleConfig) created above
  • privateKeyLoader (PrivateKeyLoaderInterface)

PrivateKeyLoaderInterface implements a loader for the private key (which you downloaded above) to create a client_secret. The user can use a pre-defined function provider.LoadApplePrivateKeyFromFile(filePath string) to load the private key from local file.

AddAppleProvider tries to load private key at call and return an error if load failed. Always check error when calling this provider.

    if err := service.AddAppleProvider(appleCfg, provider.LoadApplePrivateKeyFromFile("PATH_TO_PRIVATE_KEY_FILE")); err != nil {
		log.Fatalf("[ERROR] failed create to AppleProvider: %v", err)
	}

Limitation:

  • Apple sends the user's name only on the first authorisation. The token then carries First Last; on later logins it carries noname_ followed by 6 characters of the user id. Store the name at the first login under the user id, and do not overwrite it with a noname_ value. Email is not requested.
  • Provider always get user UID (sub claim) in IDToken.

Token validation:

The provider verifies the Apple id_token signature against Apple's published JWK, then enforces:

  • iss == "https://appleid.apple.com" -- per Apple's Sign-in-with-Apple REST API spec
  • aud == ClientID (your Service ID or App ID)

A token signed by Apple but issued for a different aud is rejected with 403 invalid id_token. The aud check (not the iss check) is what closes the confused-deputy attack: a sibling service in the same Apple developer team (or any other Sign-in-with-Apple client) holds tokens with the real Apple iss but their own aud, and could replay one of those tokens against this service if aud were not enforced.

  • Apple doesn't have an API for fetch avatar and user info.

See example before use.

Yandex Auth Provider

  1. Create a new "OAuth App": https://oauth.yandex.com/client/new
  2. Fill "App name" for your site
  3. Under Platforms select "Web services" and enter "Callback URI #1" constructed as domain + /auth/yandex/callback. ie https://example.mysite.com/auth/yandex/callback
  4. Select Permissions. You need following permissions only from the "Yandex.Passport API" section:
    • Access to user avatar
    • Access to username, first name and surname, gender
  5. Fill out the rest of fields if needed
  6. Take note of the ID and Password

For more details refer to Yandex OAuth and Yandex.Passport API documentation.

Battle.net Auth Provider

The provider uses the EU endpoints at eu.battle.net.

  1. Log into Battle.net as a developer: https://develop.battle.net/nav/login-redirect
  2. Click "+ CREATE CLIENT" https://develop.battle.net/access/clients/create
  3. For "Client name", enter whatever you want
  4. For "Redirect URLs", one of the lines must be "http[s]://your_server:port/auth/battlenet/callback", e.g. https://localhost:8443/auth/battlenet/callback or https://remark.mysite.com/auth/battlenet/callback
  5. For "Service URL", enter the URL to your site or check "I do not have a service URL for this client." checkbox if you don't have any
  6. For "Intended use", describe the application you're developing
  7. Click "Save".
  8. You can see your client ID and client secret at https://develop.battle.net/access/clients by clicking the client you created

For more details refer to Complete Guide of Battle.net OAuth API and Login Button or the official Battle.net OAuth2 guide

Patreon Auth Provider

  1. Create a new Patreon client https://www.patreon.com/portal/registration/register-clients
  2. Fill "App Name", "Description", "App Category" and "Author" for your site
  3. Under "Redirect URIs" enter the correct url constructed as domain + /auth/patreon/callback. ie https://example.mysite.com/auth/patreon/callback
  4. Take note of the Client ID and Client Secret

A user with at least one pledge gets IsPaidSub() == true.

Discord Auth Provider

  1. Log into Discord Developer Portal https://discord.com/developers/applications
  2. Click on New Application to create the application required for Oauth
  3. After filling "NAME", navigate to "OAuth2" option on the left sidebar
  4. Under "Redirects" enter the correct url constructed as domain + /auth/discord/callback. ie https://remark42.mysite.com/auth/discord/callback
  5. Take note of the CLIENT ID and CLIENT SECRET

Twitter Auth Provider

The twitter provider signs users in to X with OAuth 1.0a.

  1. Create a new app in the X Developer Console https://console.x.com
  2. On the app page, under User authentication settings, press Set up. In App permissions choose Read
  3. In Callback URI / redirect URL enter the url of your callback handler e.g. https://example.mysite.com/{route}/twitter/callback and fill in the required Website URL. X matches the callback exactly; for local development use http://127.0.0.1, not localhost
  4. Under Keys & Tokens, in OAuth 1.0a keys, take note of the Consumer Key and Consumer Key Secret; Regenerate shows a new pair. Those will be used as cid and csecret

In v2 of the library X can be used with OAuth 2.0 instead. In the same authentication settings choose Web app, automated app or bot as Type of app and take note of the Client ID and Client Secret shown on save; they are also under Keys & Tokens, in OAuth 2.0 keys. Register the provider with them as twitter_v2:

service.AddProvider("twitter_v2", "<Client ID>", "<Client Secret>")

The provider name stays twitter, so the routes and the callback url are the same as with OAuth 1.0a and users keep their ids. Register only one of twitter and twitter_v2.

User ids carry over to twitter_v2; the keys of UserAttributes have to be checked. The provider reads only id, name, username and profile_image_url, and a key is the name of one of those fields inside data of the response. name is the display name as before. screen_name is username now, id_str is id and profile_image_url_https is profile_image_url. A v1.1 field with no counterpart among the four gives an empty value.

X API access

The two providers read the user from different versions of the X API, and X decides per app which requests it answers. When X refuses the request, the callback of either provider returns 503.

  • twitter_v2 calls GET /2/users/me of API v2. Keycloak documents that it needs a paid API v2 plan, such as pay-per-use, and that with an app on the original Free plan the authorization completes and X then refuses the user request with 403. For that error xurl recommends moving the app to the Pay-per-use package and the Production environment.
  • twitter calls account/verify_credentials of API v1.1, which X lists as limited support. Its current access requirements are not known: the check below succeeded with a new app in a Pay-per-use project, and in 2022 X refused apps without Elevated access (#111).

Both providers were checked with new apps in a Pay-per-use project and no credits bought. On 20 November 2026 the account that owned the app signed in with each provider. On 23 November 2026, with another app in the Development environment, an account that did not own the app signed in with each provider as well. X charges for user reads and blocks requests once the credit balance goes negative, so these checks do not show how many sign-ins X answers before credits are bought. An app on the legacy Free plan was not checked with either provider.

XSRF Protections

By default, the XSRF protections apply whenever the JWT of a user is read from the cookie: in the Auth, AdminOnly, RBAC and Trace middlewares (a mismatch in Trace serves the request without a user), in /auth/user, /auth/status, and in the logout when the provider added first is an oauth2, oauth1 or Apple provider. Tokens from the header or the query are not checked. This will require setting a request header with a key of <XSRFHeaderKey> containing the value of the cookie named <XSRFCookieName>.

To disable all XSRF protections, set DisableXSRF to true. This should probably only be used during testing or debugging.

When setting a custom request header is not possible, such as when building a web application which is not a Single-Page-Application and HTML link tags are used to navigate pages, specific HTTP methods may be excluded using the XSRFIgnoreMethods option. For example, to disable GET requests, set this option to XSRFIgnoreMethods: []string{"GET"}. Methods are compared with the request method as they are, so write them in upper case. Adding methods other than GET to this list may result in XSRF vulnerabilities.

Browser apps: pair with http.CrossOriginProtection (Go 1.25+)

The JWT XSRF check above only fires when the JWT arrives in a cookie and only after a request reaches the auth middleware. For browser-based applications it is recommended to additionally wrap the router with http.CrossOriginProtection (Go 1.25+), which checks the browser-set Sec-Fetch-Site header (with an Origin vs Host fallback for older clients) and rejects cross-origin state-changing requests at the HTTP layer before they reach any handler:

csrf := http.NewCrossOriginProtection()
_ = csrf.AddTrustedOrigin("https://app.example.com") // for cross-origin SPAs
csrf.AddInsecureBypassPattern("POST /auth/apple/")   // Apple Sign In uses form_post

mux := http.NewServeMux()
mux.Handle("/api/", authenticator.Auth(apiHandler))

log.Fatal(http.ListenAndServe(":8080", csrf.Handler(mux)))

This is the algorithm recommended by OWASP as a primary CSRF defence. Unlike SameSite=Lax, it distinguishes same-origin from same-site, so subdomain attacks with unsafe methods such as POST are blocked; it lets GET, HEAD and OPTIONS through from any origin. It composes with the JWT XSRF: the new middleware covers browser flows, the JWT XSRF still covers API clients sending the JWT-derived header.

Applications that show user content on the auth origin

An application that renders HTML its users wrote, such as a comment with an image, lets them point a reader's browser at an auth route on the same origin. The browser sends the session cookies with that GET, and http.CrossOriginProtection allows it. User content on another origin of the same site, such as a sibling subdomain, gets the same cookies and the same answers, and the check below covers it while that content cannot run script. Two behaviours of the library matter then:

  • The login and logout handlers answer a plain GET. An image whose address is one of these routes changes the viewer's session:

    • Every logout path, /auth/logout and /auth/<provider>/logout alike, is served by the provider that was added first. The logout of a direct, verified or Telegram provider resets the cookies without looking at the request. The logout of an oauth2, oauth1 or Apple provider asks for the XSRF header, and takes the session cookie alone when DisableXSRF is set or GET is in XSRFIgnoreMethods.
    • The login of an oauth2, oauth1 or Apple provider puts its handshake token in place of the session cookie, so the viewer is signed out.
    • The login of a direct provider issues a new session for the user and passwd in the query when its CredChecker accepts them, which for an anonymous provider is any name.
    • The verified and Telegram logins issue a session for the owner of the confirmation token in their token parameter, so an image with a commenter's own token can sign a viewer in to the commenter's account.

    A login route is served by the provider named in its path, so these apply whichever provider was added first, and an application with oauth2 providers alone needs the check as well. Refuse requests that the browser marks as an embedded resource before they reach the auth handler that Service.Handlers() returns:

    func rejectEmbedded(next http.Handler) http.Handler {
    	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    		switch r.Header.Get("Sec-Fetch-Dest") {
    		case "", "empty", "document": // no fetch metadata, a fetch, a page or a login window
    			next.ServeHTTP(w, r)
    		default:
    			http.Error(w, "Access denied", http.StatusForbidden)
    		}
    	})
    }
    
    authRoutes, avaRoutes := service.Handlers()
    router.Handle("/auth/", rejectEmbedded(authRoutes)) // add auth handlers
    router.Handle("/avatar/", avaRoutes)                // add avatar handler

    Browsers send Sec-Fetch-Dest only to https and loopback addresses, and Safari only since version 16.4. A request without the header is served, so the check does nothing on other plain http sites or in older browsers. It stops embedded resources only: a link in user content that navigates the top-level page arrives as document and is served. A page that prefetches its links, with speculation rules or a prefetch script, requests a link in user content without a click, so keep the auth routes out of that prefetching.

    The handler also refuses a navigation inside a frame (Sec-Fetch-Dest: iframe). An application shown in a frame gets 403 when it opens a verified login link with a confirmation token in that frame, and has to complete that login with a fetch from inside the frame. Serving iframe as well would let <iframe src="/auth/logout"> in user content through again.

  • A token in the query is read first and is not XSRF-checked. token.Service.Get takes the parameter named by Opts.JWTQuery (token by default) ahead of the header and the cookie. The logout of an oauth2, oauth1 or Apple provider accepts a valid token there in place of the session cookie and its XSRF header. A token there that Opts.Validator or the provider check rejects leaves the cookies of the request alone: the auth middleware expires the cookies only when the rejected token is the request's own session cookie, so a link carrying a blocked token does not sign out whoever opens it. If the application does not need a session token in the URL, remove that parameter from the request before the auth middleware and the logout handler see it. Leave it on the login routes while JWTQuery is token: the verified and Telegram logins read their confirmation token from a token parameter of their own.

Status

The library was originally extracted from the remark42 project. The code is in production use on multiple sites and has proven to be stable and reliable.

Version 1.x is stable and in maintenance mode. Version 2.x is now the actively developed branch, and we recommend using it for all new projects.

Releases

Sponsor this project

Used by

Contributors

Languages