Help us shape the future of Go! Take the 2026 Go Developer Survey

provider

package
v1.27.1 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 45 Imported by: 23

Documentation

Overview

Package provider implements all oauth2, oauth1 as well as custom and direct providers

Index

Constants

View Source
const (

	// AcceptJSONHeader is the content to accept from response
	AcceptJSONHeader = "application/json"
)
View Source
const (
	// MaxHTTPBodySize defines max http body size
	MaxHTTPBodySize = 1024 * 1024
)
View Source
const TelegramAPIBaseURL = "https://api.telegram.org"

TelegramAPIBaseURL is the public Telegram bot API, used unless a caller supplies its own

Variables

This section is empty.

Functions

This section is empty.

Types

type AppleConfig added in v1.16.0

type AppleConfig struct {
	ClientID     string // the identifier Services ID for your app created in Apple developer account.
	TeamID       string // developer Team ID (10 characters), required for create JWT. It available, after signed in at developer account, by link: https://developer.apple.com/account/#/membership
	KeyID        string // private key ID  assigned to private key obtain in Apple developer account
	ResponseMode string // changes method of receiving data in callback. Default value "form_post" (https://developer.apple.com/documentation/sign_in_with_apple/request_an_authorization_to_the_sign_in_with_apple_server?changes=_1_2#4066168)
	// contains filtered or unexported fields
}

AppleConfig is the main oauth2 required parameters for "Sign in with Apple"

type AppleHandler added in v1.16.0

type AppleHandler struct {
	Params

	PrivateKeyLoader PrivateKeyLoaderInterface // custom function interface for load private key
	// contains filtered or unexported fields
}

AppleHandler implements login via Apple ID

func NewApple added in v1.16.0

func NewApple(p Params, appleCfg AppleConfig, privateKeyLoader PrivateKeyLoaderInterface) (*AppleHandler, error)

NewApple create new AppleProvider instance with a user parameters Private key must be set, when instance create call, for create `client_secret`

func (AppleHandler) AuthHandler added in v1.16.0

func (ah AppleHandler) AuthHandler(w http.ResponseWriter, r *http.Request)

AuthHandler fills user info and redirects to "from" url. This is callback url redirected locally by browser. POST /callback with the default form_post response mode, GET /callback when response mode is overridden

func (*AppleHandler) LoginHandler added in v1.16.0

func (ah *AppleHandler) LoginHandler(w http.ResponseWriter, r *http.Request)

LoginHandler - GET */{provider-name}/login

func (AppleHandler) LogoutHandler added in v1.16.0

func (ah AppleHandler) LogoutHandler(w http.ResponseWriter, r *http.Request)

LogoutHandler - GET /logout

func (*AppleHandler) Name added in v1.16.0

func (ah *AppleHandler) Name() string

Name of the provider

type AvatarSaver

type AvatarSaver interface {
	Put(u token.User, client *http.Client) (avatarURL string, err error)
}

AvatarSaver defines minimal interface to save avatar

type BearerTokenHook added in v1.21.0

type BearerTokenHook func(provider string, user token.User, token oauth2.Token)

BearerTokenHook accepts provider name, user and token, received during oauth2 authentication

type ContextSender added in v1.26.0

type ContextSender interface {
	SendContext(ctx context.Context, address, text string) error
}

ContextSender is an optional extension of Sender. A Sender implementing it gets the request context, so the delivery is bound to the request instead of running until the transport times out on its own.

type CredChecker added in v0.2.0

type CredChecker interface {
	Check(user, password string) (ok bool, err error)
}

CredChecker defines interface to check credentials

type CredCheckerFunc added in v0.2.0

type CredCheckerFunc func(user, password string) (ok bool, err error)

CredCheckerFunc type is an adapter to allow the use of ordinary functions as CredsChecker.

func (CredCheckerFunc) Check added in v0.2.0

func (f CredCheckerFunc) Check(user, password string) (ok bool, err error)

Check calls f(user,passwd)

type CustomHandlerOpt added in v0.8.0

type CustomHandlerOpt struct {
	Endpoint          oauth2.Endpoint
	InfoURL           string
	MapUserFn         func(UserData, []byte) token.User
	BearerTokenHookFn BearerTokenHook
	Scopes            []string
}

CustomHandlerOpt are options to initialize a handler for oauth2 server

type CustomServer added in v0.8.0

type CustomServer struct {
	logger.L
	URL              string                                       // root url for custom oauth2 server
	WithLoginPage    bool                                         // redirect to login html page if true
	LoginPageHandler func(w http.ResponseWriter, r *http.Request) // handler for user-defined login page
	OauthServer      *goauth2.Server                              // an instance of go-oauth2/oauth2 server
	HandlerOpt       CustomHandlerOpt
	// contains filtered or unexported fields
}

CustomServer is a wrapper over go-oauth2/oauth2 server running on its own port

func NewCustomServer added in v0.8.0

func NewCustomServer(srv *goauth2.Server, sopts CustomServerOpt) *CustomServer

NewCustomServer is helper function to initiate a customer server and prefill options needed for provider registration (see Service.AddCustomProvider)

func (*CustomServer) Run added in v0.8.0

func (c *CustomServer) Run(ctx context.Context)

Run starts serving on port from c.URL

func (*CustomServer) Shutdown added in v0.8.0

func (c *CustomServer) Shutdown()

Shutdown go-oauth2/oauth2 server

type CustomServerOpt added in v0.8.0

type CustomServerOpt struct {
	logger.L
	URL              string
	WithLoginPage    bool
	LoginPageHandler func(w http.ResponseWriter, r *http.Request)
}

CustomServerOpt are options to initialize a custom go-oauth2/oauth2 server

type DevAuthServer

type DevAuthServer struct {
	logger.L
	Provider   Oauth2Handler
	Automatic  bool
	GetEmailFn func(string) string
	// contains filtered or unexported fields
}

DevAuthServer is a fake oauth server for development it provides stand-alone server running on its own port and pretending to be the real oauth2. It also provides Dev Provider the same way as normal providers do, i.e. like github, google and others. can run in interactive and non-interactive mode. In interactive mode login attempts will show login form to select desired user name, this is the mode used for development. Non-interactive mode for tests only.

func (*DevAuthServer) Run

func (d *DevAuthServer) Run(ctx context.Context)

Run oauth2 dev server on port devAuthPort

func (*DevAuthServer) Shutdown

func (d *DevAuthServer) Shutdown()

Shutdown oauth2 dev server

type DirectHandler added in v0.2.0

type DirectHandler struct {
	logger.L
	CredChecker  CredChecker
	ProviderName string
	TokenService TokenService
	Issuer       string
	AvatarSaver  AvatarSaver
	UserIDFunc   UserIDFunc
}

DirectHandler implements non-oauth2 provider authorizing user in traditional way with storage with users and hashes

func (DirectHandler) AuthHandler added in v0.2.0

func (p DirectHandler) AuthHandler(http.ResponseWriter, *http.Request)

AuthHandler doesn't do anything for direct login as it has no callbacks

func (DirectHandler) LoginHandler added in v0.2.0

func (p DirectHandler) LoginHandler(w http.ResponseWriter, r *http.Request)

LoginHandler checks "user" and "passwd" against data store and makes jwt if all passed.

GET /something?user=name&passwd=xyz&aud=bar&session=[0|1]

POST /something?session=[0|1] Accepts application/x-www-form-urlencoded or application/json encoded requests.

application/x-www-form-urlencoded body example: user=name&passwd=xyz&aud=bar

application/json body example:

{
  "user": "name",
  "passwd": "xyz",
  "aud": "bar",
}

func (DirectHandler) LogoutHandler added in v0.2.0

func (p DirectHandler) LogoutHandler(w http.ResponseWriter, _ *http.Request)

LogoutHandler - GET /logout

func (DirectHandler) Name added in v0.2.0

func (p DirectHandler) Name() string

Name of the handler

type LoadFromFileFunc added in v1.16.0

type LoadFromFileFunc struct {
	Path string
}

LoadFromFileFunc is the type for use pre-defined private key loader function Path field must be set with actual path to private key file

func LoadApplePrivateKeyFromFile added in v1.16.0

func LoadApplePrivateKeyFromFile(path string) LoadFromFileFunc

LoadApplePrivateKeyFromFile return instance for pre-defined loader function from local file

func (LoadFromFileFunc) LoadPrivateKey added in v1.16.0

func (lf LoadFromFileFunc) LoadPrivateKey() ([]byte, error)

LoadPrivateKey implement pre-defined (built-in) PrivateKeyLoaderInterface interface method for load private key from local file

type Oauth1Handler added in v0.8.0

type Oauth1Handler struct {
	Params
	// contains filtered or unexported fields
}

Oauth1Handler implements /login, /callback and /logout handlers for oauth1 flow

func NewTwitter added in v0.8.0

func NewTwitter(p Params) Oauth1Handler

NewTwitter makes twitter oauth2 provider

func (Oauth1Handler) AuthHandler added in v0.8.0

func (h Oauth1Handler) AuthHandler(w http.ResponseWriter, r *http.Request)

AuthHandler fills user info and redirects to "from" url. This is callback url redirected locally by browser GET /callback

func (Oauth1Handler) LoginHandler added in v0.8.0

func (h Oauth1Handler) LoginHandler(w http.ResponseWriter, r *http.Request)

LoginHandler - GET /login?from=redirect-back-url&site=siteID&session=1

func (Oauth1Handler) LogoutHandler added in v0.8.0

func (h Oauth1Handler) LogoutHandler(w http.ResponseWriter, r *http.Request)

LogoutHandler - GET /logout

func (Oauth1Handler) Name added in v0.8.0

func (h Oauth1Handler) Name() string

Name returns provider name

type Oauth2Handler added in v0.1.1

type Oauth2Handler struct {
	Params
	// contains filtered or unexported fields
}

Oauth2Handler implements /login, /callback and /logout handlers from aouth2 flow

func NewBattlenet added in v0.11.0

func NewBattlenet(p Params) Oauth2Handler

NewBattlenet makes Battle.net oauth2 provider

func NewCustom added in v0.8.0

func NewCustom(name string, p Params, copts CustomHandlerOpt) Oauth2Handler

NewCustom creates a handler for go-oauth2/oauth2 server

func NewDev

func NewDev(p Params) Oauth2Handler

NewDev makes a dev oauth2 provider intended for local development only.

func NewDiscord added in v1.25.0

func NewDiscord(p Params) Oauth2Handler

NewDiscord makes discord oauth2 provider

func NewFacebook

func NewFacebook(p Params) Oauth2Handler

NewFacebook makes facebook oauth2 provider

func NewGithub

func NewGithub(p Params) Oauth2Handler

NewGithub makes github oauth2 provider

func NewGoogle

func NewGoogle(p Params) Oauth2Handler

NewGoogle makes google oauth2 provider

func NewMicrosoft added in v0.11.0

func NewMicrosoft(p Params) Oauth2Handler

NewMicrosoft makes microsoft azure oauth2 provider

func NewPatreon added in v1.18.0

func NewPatreon(p Params) Oauth2Handler

NewPatreon makes patreon oauth2 provider

func NewYandex

func NewYandex(p Params) Oauth2Handler

NewYandex makes yandex oauth2 provider

func (Oauth2Handler) AuthHandler added in v0.1.1

func (p Oauth2Handler) AuthHandler(w http.ResponseWriter, r *http.Request)

AuthHandler fills user info and redirects to "from" url. This is callback url redirected locally by browser GET /callback

func (Oauth2Handler) LoginHandler added in v0.1.1

func (p Oauth2Handler) LoginHandler(w http.ResponseWriter, r *http.Request)

LoginHandler - GET /login?from=redirect-back-url&[site|aud]=siteID&session=1&noava=1

func (Oauth2Handler) LogoutHandler added in v0.1.1

func (p Oauth2Handler) LogoutHandler(w http.ResponseWriter, r *http.Request)

LogoutHandler - GET /logout

func (Oauth2Handler) Name added in v0.1.1

func (p Oauth2Handler) Name() string

Name returns provider name

type Params

type Params struct {
	logger.L
	URL            string
	JwtService     TokenService
	Cid            string
	Csecret        string
	Issuer         string
	AvatarSaver    AvatarSaver
	UserAttributes UserAttributes

	// AllowedRedirectHosts lists hostnames accepted in the "from" query
	// parameter. Setting this field enables host validation: the host of
	// URL is always implicit, and any other host must appear here. Nil
	// disables validation and preserves legacy permissive behavior — any
	// non-empty "from" value is honored. See isAllowedRedirect for the
	// full policy.
	AllowedRedirectHosts token.AllowedHosts

	Port int    // relevant for providers supporting port customization, for example dev oauth2
	Host string // relevant for providers supporting host customization, for example dev oauth2

	MicrosoftTenant string // tenant for microsoft provider, default "common"

	// GithubNumericID makes github provider derive the user id from the immutable numeric account id
	// instead of the login. Logins are released on rename or account removal and can be claimed by
	// someone else, so an id derived from login may be inherited by the next holder of the name.
	// Enabling this changes the id of every existing github user, see README for the migration note.
	// Best-effort: if the response carries no usable numeric id the login-derived id is kept.
	GithubNumericID bool
}

Params to make initialized and ready to use provider

type PrivateKeyLoaderInterface added in v1.16.0

type PrivateKeyLoaderInterface interface {
	LoadPrivateKey() ([]byte, error)
}

PrivateKeyLoaderInterface interface for implement custom loader for Apple private key from user source

type Provider added in v0.1.1

type Provider interface {
	Name() string
	LoginHandler(w http.ResponseWriter, r *http.Request)
	AuthHandler(w http.ResponseWriter, r *http.Request)
	LogoutHandler(w http.ResponseWriter, r *http.Request)
}

Provider defines interface for auth handler

type Sender added in v0.6.0

type Sender interface {
	Send(address, text string) error
}

Sender defines interface to deliver a verification message (email, IM, or anything else).

type SenderFunc added in v0.6.0

type SenderFunc func(address, text string) error

SenderFunc type is an adapter to allow the use of ordinary functions as Sender.

func (SenderFunc) Send added in v0.6.0

func (f SenderFunc) Send(address, text string) error

Send calls f(address,text) to implement Sender interface

type Service

type Service struct {
	Provider
}

Service represents oauth2 provider. Adds Handler method multiplexing login, auth and logout requests

func NewService added in v0.1.1

func NewService(p Provider) Service

NewService makes service for given provider

func (Service) Handler

func (p Service) Handler(w http.ResponseWriter, r *http.Request)

Handler dispatches login, callback, and logout requests to the underlying provider.

type TelegramAPI added in v1.5.1

type TelegramAPI interface {
	GetUpdates(ctx context.Context) (*telegramUpdate, error)
	Avatar(ctx context.Context, userID int) (string, error)
	Send(ctx context.Context, id int, text string) error
	BotInfo(ctx context.Context) (*botInfo, error)
}

TelegramAPI is used for interacting with telegram API

func NewTelegramAPI added in v1.5.1

func NewTelegramAPI(token string, client *http.Client) TelegramAPI

NewTelegramAPI returns initialized TelegramAPI implementation

func NewTelegramAPIWithBaseURL added in v1.27.0

func NewTelegramAPIWithBaseURL(token string, client *http.Client, baseURL string) (TelegramAPI, error)

NewTelegramAPIWithBaseURL makes a Telegram API client talking to baseURL instead of the public API. Intended for a proxy in front of Telegram and for tests that need to answer as Telegram; every request the client makes goes through it, avatar downloads included, so the production path stays the code under test. Both forms are derived from it, as baseURL/bot<token>/<method> and baseURL/file/bot<token>/<path>.

An empty baseURL falls back to the public API. Anything else has to be an absolute http or https URL with a host and no userinfo, query, fragment or opaque part, since every request carries the bot token in its path and a malformed base sends it somewhere else. A path prefix is allowed, for a proxy mounted under one.

Redirects are refused by default, because Go copies the previous URL into Referer on any hop that is not https-to-http and every URL here carries the token. A client arriving with its own CheckRedirect keeps it: that hook is this caller's policy about a base they chose, and following a redirect under it hands the token to the destination unless the hook strips the header or refuses the hop itself.

type TelegramHandler added in v1.5.1

type TelegramHandler struct {
	logger.L

	ProviderName         string
	ErrorMsg, SuccessMsg string

	TokenService TokenService
	AvatarSaver  AvatarSaver
	Telegram     TelegramAPI
	// contains filtered or unexported fields
}

TelegramHandler implements login via telegram

func (*TelegramHandler) AuthHandler added in v1.5.1

func (th *TelegramHandler) AuthHandler(_ http.ResponseWriter, _ *http.Request)

AuthHandler does nothing since we don't have any callbacks

func (*TelegramHandler) LoginHandler added in v1.5.1

func (th *TelegramHandler) LoginHandler(w http.ResponseWriter, r *http.Request)

LoginHandler generates and verifies login requests

func (*TelegramHandler) LogoutHandler added in v1.5.1

func (th *TelegramHandler) LogoutHandler(w http.ResponseWriter, _ *http.Request)

LogoutHandler - GET /logout

func (*TelegramHandler) Name added in v1.5.1

func (th *TelegramHandler) Name() string

Name of the provider

func (*TelegramHandler) ProcessUpdate added in v1.19.0

func (th *TelegramHandler) ProcessUpdate(ctx context.Context, textUpdate string) error

ProcessUpdate is alternative to Run, it processes provided plain text update from Telegram so that caller could get updates and send it not only there but to multiple sources

func (*TelegramHandler) Run added in v1.5.1

func (th *TelegramHandler) Run(ctx context.Context) error

Run starts processing login requests sent in Telegram Blocks caller

func (*TelegramHandler) String added in v1.19.0

func (th *TelegramHandler) String() string

String representation of the provider

type TokenService

type TokenService interface {
	Parse(tokenString string) (claims token.Claims, err error)
	Set(w http.ResponseWriter, claims token.Claims) (token.Claims, error)
	Get(r *http.Request) (claims token.Claims, token string, err error)
	Reset(w http.ResponseWriter)
}

TokenService defines interface accessing tokens

type UserAttributes added in v1.22.1

type UserAttributes map[string]string

UserAttributes is the type that will be used to map user data from provider to token.User

type UserData added in v0.8.0

type UserData map[string]any

UserData is type for user information returned from oauth2 providers /info API method

func (UserData) Value added in v0.8.0

func (u UserData) Value(key string) string

Value returns value for key or empty string if not found

type UserIDFunc added in v1.18.0

type UserIDFunc func(user string, r *http.Request) string

UserIDFunc allows to provide custom func making userID instead of the default based on user's name hash

type VerifConfirmationStore added in v1.25.3

type VerifConfirmationStore interface {
	// MarkUsed records key as consumed and returns alreadyUsed=true if it was
	// already recorded. The implementation MUST retain the marker for at
	// least the supplied ttl, or return a non-nil err if it cannot --
	// dropping a marker before its ttl while the underlying JWT is still
	// valid reopens the replay window the store is meant to close. err
	// signals a backend failure (network, disk, capacity, etc.); callers
	// MUST treat a non-nil err as fail-closed (reject the redemption).
	//
	// Adapter authors: do NOT embed key (or any caller-supplied data) in
	// returned errors. The handler logs err on the fail-closed branch, and
	// although key is the SHA-256 of the raw token rather than the token
	// itself, it still uniquely identifies the live, unredeemed JWT in
	// log destinations. Wrap the underlying backend error with a generic
	// description (e.g. "redis SET failed: %w") instead.
	MarkUsed(key string, ttl time.Duration) (alreadyUsed bool, err error)
}

VerifConfirmationStore tracks consumed confirmation tokens to prevent replay. Implementations must be safe for concurrent use.

func NewInMemoryVerifStore added in v1.25.3

func NewInMemoryVerifStore() VerifConfirmationStore

NewInMemoryVerifStore returns a process-local default VerifConfirmationStore. Suitable for single-instance deployments. Multi-instance deployments behind a load balancer MUST supply a shared backend (e.g. Redis) -- otherwise an attacker who lands on a different instance from the legitimate user can replay the token there. The default's failure is silent: the request completes normally and no log indicates the protection was bypassed.

type VerifConfirmationStoreFunc added in v1.25.3

type VerifConfirmationStoreFunc func(key string, ttl time.Duration) (alreadyUsed bool, err error)

VerifConfirmationStoreFunc is an adapter to use ordinary functions as VerifConfirmationStore, mirroring the SenderFunc / token.AllowedHostsFunc house pattern for closure-based config.

func (VerifConfirmationStoreFunc) MarkUsed added in v1.25.3

func (f VerifConfirmationStoreFunc) MarkUsed(key string, ttl time.Duration) (bool, error)

MarkUsed calls f(key, ttl) to implement VerifConfirmationStore.

type VerifTokenService added in v0.6.0

type VerifTokenService interface {
	Token(claims token.Claims) (string, error)
	Parse(tokenString string) (claims token.Claims, err error)
	IsExpired(claims token.Claims) bool
	Set(w http.ResponseWriter, claims token.Claims) (token.Claims, error)
	Reset(w http.ResponseWriter)
}

VerifTokenService defines interface accessing tokens

type VerifyHandler added in v0.6.0

type VerifyHandler struct {
	logger.L
	ProviderName string
	TokenService VerifTokenService
	Issuer       string
	AvatarSaver  AvatarSaver
	Sender       Sender
	Template     string
	UseGravatar  bool

	// URL is the service's own root URL; its host is always permitted as
	// a "from" redirect target. Optional but recommended.
	URL string
	// AllowedRedirectHosts lists additional hostnames permitted as "from"
	// redirect targets. Setting this field enables host validation: the
	// host of URL is always implicit, and any other host must appear
	// here. Nil disables validation and preserves legacy permissive
	// behavior — any non-empty "from" value is honored.
	AllowedRedirectHosts token.AllowedHosts

	// ConfirmationStore enforces one-shot consumption of confirmation tokens.
	// When non-nil, a token cannot be redeemed twice within its TTL window.
	// Leave nil to keep the legacy behavior (token replayable until expiry).
	ConfirmationStore VerifConfirmationStore
}

VerifyHandler implements non-oauth2 provider authorizing users with some confirmation. can be email, IM or anything else implementing Sender interface

Identity caveat: the local user id returned to the application is derived from the verified address (ProviderName + "_" + HashID(address)). The confirmation round-trip proves current control of the address at login time; it does not guarantee a stable+unique identity over time. The owner of an address can change without the address changing — employer offboarding, lapsed free-mail accounts, and recycled domains all hand control of an address to the next person who claims it. Integrators that need stable identity should map the verified address to a server-side immutable user id at first successful verify and key their records on that id, not on the value returned here. See the "Email-as-identity caveat" section of the README for guidance.

func (VerifyHandler) AuthHandler added in v0.6.0

func (e VerifyHandler) AuthHandler(http.ResponseWriter, *http.Request)

AuthHandler is a no-op for verify login — the flow has no provider callback.

func (VerifyHandler) LoginHandler added in v0.6.0

func (e VerifyHandler) LoginHandler(w http.ResponseWriter, r *http.Request)

LoginHandler gets name and address from query, makes confirmation token and sends it to user. In case if confirmation token presented in the query uses it to create auth token.

Consumption is final when ConfirmationStore is configured: the token is marked used before any further side effects (avatar fetch, token issuance), so a transient downstream failure burns the token and the user must request a new confirmation email rather than retry the same link. This trade-off keeps the replay check atomic with the security boundary.

func (VerifyHandler) LogoutHandler added in v0.6.0

func (e VerifyHandler) LogoutHandler(w http.ResponseWriter, _ *http.Request)

LogoutHandler - GET /logout

func (VerifyHandler) Name added in v0.6.0

func (e VerifyHandler) Name() string

Name of the handler

Directories

Path Synopsis
Package sender provides email sender
Package sender provides email sender

Jump to

Keyboard shortcuts

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