← Back to archive

Repo of the Day

go-pkgz/auth

Published: May 13, 2024

Open repository ↗

Authenticator via oauth2, direct, email and telegram for Go.

Summary

go-pkgz/auth is a Go library that adds authentication to HTTP services through OAuth2 social logins, custom OAuth2 servers, direct credential checks, and email or Telegram confirmation flows. It also bundles an avatar proxy with multiple storage backends and middleware for protecting routes, including role-based access control. The current v2 release uses github.com/golang-jwt/jwt/v5 and is the recommended version for new projects, while the v1 line is described as legacy.

What it is useful for

This library fits when a Go web service needs pluggable login options without hand-rolling each provider. It ships with built-in support for GitHub, Google, Facebook, Microsoft, Twitter, Yandex, Battle.net, Apple, Patreon, Discord, and Telegram, and it can be extended to any third-party OAuth2 server by supplying an endpoint, an info URL, a scope, and a MapUserFn (the README demonstrates this for Bitbucket). Beyond OAuth2, it offers a dev provider for local testing, a direct provider for username/password checks against a user-defined credential function, and a verified provider that sends confirmation tokens through any user-implemented Sender; an email client lives in the provider/sender package. JWTs are stored in a secure cookie with XSRF protection, and middleware can extract the current user from the request context. Avatar URLs from social providers are proxied automatically and cached in LocalFS, BoltDB, GridFS, or a custom store, which avoids throttling on the original host and falls back to identicons for users without pictures. Middleware helpers cover Auth, Admin, Trace, and role-based access control.

How engineers can use it

Install with go get -u github.com/go-pkgz/auth/v2, build an auth.Opts struct with at least a SecretReader, Issuer, URL, and an AvatarStore, then call auth.NewService(options). Register providers with service.AddProvider("github", cid, csecret), optionally add direct or verified providers, and mount the returned Handlers() under /auth/ and /avatar/. Apply service.Middleware() to routes that require auth, and read the user inside handlers via token.GetUserInfo(r). Direct providers use service.AddDirectProvider("local", provider.CredCheckerFunc(...)), while the verified provider takes a message template and a Sender. Telegram requires creating a bot with BotFather and registering a TelegramHandler via service.AddCustomHandler. The README documents two limitations to plan around: the default confirmation-token replay store is in-memory, so multi-instance deployments must supply a shared backend through Opts.VerifConfirmationStore or replay protection is bypassed silently; and the email verify provider returns an id derived from the address, so applications that need stable identity across address ownership changes should map it to a server-side user record.