Documentation
¶
Overview ¶
Package auth answers two questions for any part of an application: who is acting, and does this user exist. Authentication of HTTP requests, the application user lookup and the cleanup of user data share one vocabulary, the subject, and none of them needs to know the application's user type. Authorization lives in the gate subpackage, and authtest checks drivers and authenticators.
Identity ¶
An Identity says who is acting: a Identity.Subject, the Factor values that were verified, the granted Identity.Scopes, an optional Identity.Actor and the UserRecord the authenticator resolved. It is an immutable value built with NewIdentity and read from a context with FromContext, so jobs, MCP tools and arks can use it without importing the application's user type. Identity.Level is derived from the factors: LevelNone without factors, LevelSingle for factors of one kind and LevelMulti for two distinct kinds among KindKnowledge, KindPossession and KindInherence. KindFederated never counts toward LevelMulti.
A request authenticator may attach the application's own user to the record. UserFromContext returns it by type, and a value of another type is reported as absent, so a mismatch fails closed.
Authenticating requests ¶
An Authenticator turns a request into an Identity. It returns ErrNoCredentials when the request has nothing it understands, so Middleware tries the next one; any other error stops the request. Anonymous requests continue without an identity; Require rejects them. Bearer adapts a token verifier. Require uses MiddlewareBuilder construction policies.
Browser sessions use Login, described below. Its Login.Authenticator reads the session record, asks the UserProvider on every request and builds an identity with the stored factors and the provider's UserRecord.
Wiring ¶
Order matters: session, then authentication, then everything that needs the identity (rate limits keyed by user, routes).
r := router.New()
driver, err := auth.NewUserDriver(loadUser, userID)
if err != nil {
return err
}
users, err := auth.NewUserProvider(driver)
if err != nil {
return err
}
login, err := auth.NewLogin(users, store)
if err != nil {
return err
}
r.Use(session.Middleware(store))
r.Use(csrf.Middleware())
r.Use(auth.Middleware(login.Authenticator(), auth.Bearer(verifyKey)))
r.Use(ratelimit.Middleware(store, func(limiter *ratelimit.Builder) {
limiter.KeyFunc(func(r *http.Request) string {
if current, err := request.Identity(r); err == nil {
return "user:" + current.Subject()
}
return "ip:" + r.RemoteAddr
})
}))
r.Post("/login", signIn)
r.Post("/logout", signOut)
private := r.With(auth.Require())
private.Get("/me", me)
r.With(gate.Require(isAdmin)).Delete("/users/{id}", deleteUser)
Login, levels and step-up ¶
Login turns "this person proved X" into a logged-in session. Every login method (password, OAuth, SAML, passkey) verifies its own credential and then calls Login.Begin with the subject and the verified Factor. Begin looks the user up with the provider (a deleted or disabled user is ErrUnauthenticated) and asks each check registered with LoginBuilder.SecondFactor, so core never imports the package that knows whether a user is enrolled. If none says yes the user is logged in and Begin returns true. Otherwise the login is parked as pending and the request stays anonymous: the handler asks for the second factor, reads the user with Login.Pending, reports a wrong code with Login.Fail (the pending login is discarded after LoginBuilder.MaxAttempts) and finishes with Login.Complete, which is single use. LoginBuilder.ChallengeTTL bounds the wait. Login.Confirm records a fresh factor on a logged-in session, such as a re-entered password. Every transition regenerates the session ID.
The session holds one record (subject, factors, a hash of the user's UserRecord.Version and a login-record ID) under one key, and a pending login under another. The authenticator compares the version in constant time, so changing the version ends every other session of the user. Sessions written before this layout, under "arkoren:auth:user", are anonymous.
Devices ¶
Every login (Begin without a second factor, and Complete) creates a LoginRecord with a random ID that survives session ID rotation. All records of a user live in one entry of the cache given to NewLogin, under "arkoren:auth:logins", whose lifetime is LoginBuilder.SessionLifetime (set it to the session middleware's maximum lifetime). Login.Logins lists them and flags the current one, Login.Revoke, Login.RevokeOthers and Login.RevokeAll log devices out, and Login.LoginsOf serves administrators. The authenticator reads the entry on every request and treats a missing record as ErrNoCredentials, so a revoked device cannot list or revoke devices either; it refreshes LoginRecord.SeenAt at most every five minutes, ignoring a failed write. Records older than the session lifetime are never listed and the next write removes them. At most LoginBuilder.MaxLogins records are kept and the oldest is dropped, which logs that device out. Login.Logout removes its record and NewLogin registers Login.RevokeAll with UserProvider.OnForget.
Records hold the user agent (cut to 255 bytes) and client address, which are personal data: LoginBuilder.Devices turns them off, and they never enter telemetry or events. The address is the host of r.RemoteAddr unless LoginBuilder.ClientIP says otherwise; behind a reverse proxy pass ratelimit.TrustedProxyKey from core/http/middleware/ratelimit with your proxy prefixes (it reports IPv6 addresses as their /64 prefix). Writes take a per-user cache lock and compare-and-put with a bounded retry. A flushed cache logs everyone out, and each authenticated session request costs one extra cache read.
RequireLevel and RequireFresh guard routes by the factors of the identity in the context, so they also work for tokens that carry factors. Too weak or too old is ErrStepUpRequired (403); no identity is rejected like Require. A factor dated in the future is not fresh.
Hash passwords with the hash package. Precompute dummyHash at startup with the same hasher and cost as real passwords. Checking it for unknown emails reduces timing differences; it does not guarantee identical request times. A missing account or password mismatch is a credential rejection; return database and hash failures without replacing them with ErrUnauthenticated. JSON v2 matches field names case-sensitively, so tag the lower-case request members:
func signIn(w http.ResponseWriter, r *http.Request) error {
in, err := request.JSON[struct {
Email string `json:"email"`
Password string `json:"password"`
}](r)
if err != nil {
return err
}
user, err := db.Find[User](r.Context(), query.Table("users", func(statement *query.Builder) {
statement.Where("email", in.Email)
}))
if err != nil && !errors.Is(err, database.ErrNoRows) {
return err
}
found := err == nil
hashed := dummyHash
if found {
hashed = user.PasswordHash
}
ok, err := hasher.CheckRaw([]byte(in.Password), hashed)
if err != nil {
return err
}
if !found || !ok {
return auth.ErrUnauthenticated
}
subject, err := driver.Subject(user) // the user driver of the wiring above
if err != nil {
return err
}
factor := auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
complete, err := login.Begin(r, subject, factor)
if err != nil {
return err
}
if !complete {
return response.Status(w, http.StatusAccepted) // ask for the second factor
}
return response.Status(w, http.StatusNoContent)
}
func signOut(w http.ResponseWriter, r *http.Request) error {
if err := login.Logout(r); err != nil {
return err
} // or Destroy() to drop all data
return response.Status(w, http.StatusNoContent)
}
r.With(auth.RequireLevel(auth.LevelMulti)).Post("/payouts", payout)
r.With(auth.RequireFresh(10 * time.Minute)).Delete("/account", destroy)
Cookie authentication needs CSRF protection ¶
Browsers send session cookies on cross-site requests, so install csrf.Middleware whenever Login authenticates browser cookies.
Deleted users ¶
Sessions outlive accounts. Login.Authenticator asks the provider on every request, and a user that is deleted (ErrUserNotFound) or disabled (ErrUserDisabled) becomes anonymous instead of failing with a 500.
API keys ¶
Look the key up by a non-secret id or hash, and compare secrets in constant time. Bearer validates the header, not your application's key format: even a one-byte token reaches the verifier. This application uses an eight-byte lookup prefix and stores the full token's SHA-256 hash in key.Hash. Reject short tokens before slicing them:
auth.Bearer(func(ctx context.Context, token string) (auth.Identity, error) {
const prefixLength = 8
if len(token) < prefixLength {
return auth.Identity{}, auth.ErrUnauthenticated
}
key, err := keys.ByPrefix(ctx, token[:prefixLength])
if err != nil {
return auth.Identity{}, err
}
sum := sha256.Sum256([]byte(token))
if subtle.ConstantTimeCompare(sum[:], key.Hash) != 1 {
return auth.Identity{}, auth.ErrUnauthenticated
}
return auth.NewIdentity(key.OwnerSubject, func(principal *auth.IdentityBuilder) {
principal.Scopes(key.Scopes...)
}), nil
})
keys.ByPrefix is application code. It must reject unknown or revoked keys with an error other than ErrNoCredentials, which would allow anonymous fallback. Bearer wraps lookup failures as 401 responses while retaining their causes; do not include tokens in errors that can reach logs.
JWT bearer tokens ¶
Verify the signature and claims in the verify function and build the identity from the claims without a database call. The trade-off is revocation lag: a token stays valid until it expires, so keep lifetimes short.
OAuth2 and OIDC ¶
The driver/oauth/oauthauth package plugs into auth without auth importing it. See its package documentation for the setup; it is updated for the non-generic Authenticator in a later release.
Subjects ¶
A subject is the stable text reference of a user: 1 to 255 bytes of printable ASCII without spaces. It is case sensitive and compared bytewise. ValidateSubject checks the rule; ErrInvalidSubject reports a violation. NewUserDriver converts between a typed identifier and its subject: strings are used as is, integers become decimal digits, and types implementing encoding.TextMarshaler and (through a pointer) encoding.TextUnmarshaler use their text form. Parsing is canonical: a subject that does not render back to itself, such as "007" or "+1" for an integer, is an invalid subject.
Looking up users ¶
A UserDriver finds one UserRecord by subject. Wrap it with NewUserProvider and call UserProvider.Find. A missing user is ErrUserNotFound; a user that exists but may not act is ErrUserDisabled. Only ErrUserNotFound proves a user is deleted, so cleanup code must never treat any other error as deletion.
Forgetting users ¶
Packages that store data about users register a hook with UserProvider.OnForget. UserProvider.Forget runs the hooks in registration order in the caller's context, so hooks join the caller's database transaction. The first error stops the run and is returned. When every hook succeeded, Forget emits UserForgotten on the bus given to UserProviderBuilder.Events; without a bus nothing is emitted.
Events ¶
With MiddlewareBuilder.Events, Require publishes Rejected ("http.auth.rejected") with the method of every anonymous request it rejects. The response defaults to 401; ErrorResponse can replace it. Paths are not published because they can contain identifiers or credentials. Clients control the event rate, so listeners must be cheap and a rate limiter should sit in front of Require. Payloads carry no identity, credentials, query, or cause. Event contexts still retain request context values; listeners must select safe attributes. These payload limits do not change HTTP problem instance rendering.
UserForgotten ("auth.user.forgotten") carries only the subject. It means the forget hooks completed, not that a surrounding transaction committed.
Drivers and tests ¶
arkoren.dev/core/auth/memoryauth is an in-memory user driver and arkoren.dev/core/auth/authtest holds the conformance suites: one for every user driver and one for every Authenticator.
Example:
driver, err := auth.NewUserDriver(loadUser, func(user User) int64 { return user.ID })
if err != nil {
return err
}
users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
users.Events(app.Events())
})
if err != nil {
return err
}
record, err := users.Find(ctx, "42")
Index ¶
- Variables
- func Middleware(authenticators ...Authenticator) router.Middleware
- func NewContext(ctx context.Context, identity Identity) context.Context
- func Require(configure ...MiddlewareBuilderFunc) router.Middleware
- func RequireFresh(maxAge time.Duration, configure ...MiddlewareBuilderFunc) router.Middleware
- func RequireLevel(level Level, configure ...MiddlewareBuilderFunc) router.Middleware
- func UserFromContext[U any](ctx context.Context) (U, bool)
- func ValidateSubject(subject string) error
- type Authenticator
- type Factor
- type Identity
- type IdentityBuilder
- func (principal *IdentityBuilder) Actor(actor string) *IdentityBuilder
- func (principal *IdentityBuilder) Factors(factors ...Factor) *IdentityBuilder
- func (principal *IdentityBuilder) Record(record UserRecord) *IdentityBuilder
- func (principal *IdentityBuilder) Scopes(scopes ...string) *IdentityBuilder
- type IdentityBuilderFunc
- type Kind
- type Level
- type Login
- func (login *Login) Authenticator() Authenticator
- func (login *Login) Begin(r *http.Request, subject string, factor Factor) (complete bool, err error)
- func (login *Login) Complete(r *http.Request, factor Factor) error
- func (login *Login) Confirm(r *http.Request, factor Factor) error
- func (login *Login) Fail(r *http.Request) error
- func (login *Login) Logins(r *http.Request) ([]LoginRecord, error)
- func (login *Login) LoginsOf(ctx context.Context, subject string) ([]LoginRecord, error)
- func (login *Login) Logout(r *http.Request) error
- func (login *Login) Pending(r *http.Request) (UserRecord, error)
- func (login *Login) Revoke(ctx context.Context, subject string, ids ...string) error
- func (login *Login) RevokeAll(ctx context.Context, subject string) error
- func (login *Login) RevokeOthers(r *http.Request) error
- type LoginBuilder
- func (policy *LoginBuilder) ChallengeTTL(ttl time.Duration) *LoginBuilder
- func (policy *LoginBuilder) ClientIP(find func(*http.Request) string) *LoginBuilder
- func (policy *LoginBuilder) Devices(enabled bool) *LoginBuilder
- func (policy *LoginBuilder) Handle(handle session.Handle) *LoginBuilder
- func (policy *LoginBuilder) MaxAttempts(attempts int) *LoginBuilder
- func (policy *LoginBuilder) MaxLogins(limit int) *LoginBuilder
- func (policy *LoginBuilder) SecondFactor(check func(ctx context.Context, subject string) (bool, error)) *LoginBuilder
- func (policy *LoginBuilder) SessionLifetime(lifetime time.Duration) *LoginBuilder
- type LoginBuilderFunc
- type LoginRecord
- type Method
- type MiddlewareBuilder
- type MiddlewareBuilderFunc
- type RejectedEvent
- type TypedUserDriver
- type UserDriver
- type UserDriverBuilder
- type UserDriverBuilderFunc
- type UserForgottenEvent
- type UserProvider
- type UserProviderBuilder
- type UserProviderBuilderFunc
- type UserRecord
Examples ¶
- Authenticator
- Bearer
- Factor
- FromContext
- Identity
- Identity.Actor
- Identity.Factors
- Identity.Level
- Identity.Record
- Identity.Scopes
- Identity.Subject
- IdentityBuilder
- IdentityBuilder.Actor
- IdentityBuilder.Factors
- IdentityBuilder.Record
- IdentityBuilder.Scopes
- IdentityBuilderFunc
- Kind
- Level
- Login
- Login.Authenticator
- Login.Begin
- Login.Complete
- Login.Confirm
- Login.Fail
- Login.Logins
- Login.LoginsOf
- Login.Logout
- Login.Pending
- Login.Revoke
- Login.RevokeAll
- Login.RevokeOthers
- LoginBuilder
- LoginBuilder.ChallengeTTL
- LoginBuilder.ClientIP
- LoginBuilder.Devices
- LoginBuilder.Handle
- LoginBuilder.MaxAttempts
- LoginBuilder.MaxLogins
- LoginBuilder.SecondFactor
- LoginBuilder.SessionLifetime
- LoginBuilderFunc
- LoginRecord
- Method
- Middleware
- MiddlewareBuilder
- MiddlewareBuilder.ErrorResponse
- MiddlewareBuilder.Events
- MiddlewareBuilderFunc
- NewContext
- NewIdentity
- NewLogin
- NewUserDriver
- NewUserProvider
- RejectedEvent
- Require
- RequireFresh
- RequireLevel
- TypedUserDriver
- TypedUserDriver.Find
- TypedUserDriver.Subject
- UserDriver
- UserDriverBuilder
- UserDriverBuilder.Claims
- UserDriverBuilder.Disabled
- UserDriverBuilder.Version
- UserDriverBuilderFunc
- UserForgottenEvent
- UserFromContext
- UserProvider.Find
- UserProvider.Forget
- UserProvider.OnForget
- UserProviderBuilder.Events
- UserProviderBuilderFunc
- UserRecord
- ValidateSubject
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUserNotFound reports that no user has the subject. Only this error // proves a user is deleted: code that removes data of deleted users must act // on it and on nothing else, so a disabled user's data is never removed. // A subject that cannot be parsed is [ErrInvalidSubject], never this error. // // Example: // // if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrUserNotFound) { // return users.Forget(ctx, subject) // } ErrUserNotFound = errors.New("auth: user not found") // ErrUserDisabled reports that the user exists but may not act, for example // a suspended account. The user is not deleted: keep its data. // // Example: // // if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrUserDisabled) { // return nil // Skip the user, keep the data. // } ErrUserDisabled = errors.New("auth: user disabled") )
var ErrInvalidSubject = errors.New("auth: invalid subject")
ErrInvalidSubject reports a subject that is not 1 to 255 printable ASCII bytes without spaces, a subject that does not parse as the driver's identifier type or does not render back to itself, and an identifier type that is not a string, an integer or a text-marshaling type.
Example:
if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrInvalidSubject) {
return err
}
var ErrNoCredentials = errors.New("auth: no credentials")
ErrNoCredentials is returned by an Authenticator when the request carries nothing it understands, so the next authenticator may try. Invalid credentials must return a different error to stop fallback.
Example:
if r.Header.Get("Authorization") == "" {
return auth.Identity{}, auth.ErrNoCredentials
}
var ErrStepUpRequired = problem.New(func(details *problem.Builder) { details.Type("tag:arkoren.dev,2026-11:core:auth:step-up-required") details.Title("Step-up required") details.Detail("Additional authentication is required to access this resource.") details.Status(http.StatusForbidden) })
ErrStepUpRequired is the 403 problem returned by RequireLevel and RequireFresh when an authenticated request has not proved enough, or not recently enough. A client should ask the user for the missing factor and retry. It is 403, not 401, because the user is authenticated and a 401 invites login redirects that would discard the session.
Example:
if errors.Is(err, auth.ErrStepUpRequired) {
// Ask the user to confirm, then retry.
}
var ErrUnauthenticated = problem.New(func(details *problem.Builder) { details.Type("tag:arkoren.dev,2026-09:core:http/auth:unauthenticated") details.Title("Unauthenticated") details.Detail("Authentication is required to access this resource.") details.Status(http.StatusUnauthorized) })
ErrUnauthenticated is the problem returned when a request has no authenticated identity or presents invalid credentials.
Example:
if _, err := request.Identity(r); err != nil {
return err // renders as 401
}
var Rejected = event.NewTopic[RejectedEvent]("http.auth.rejected")
Rejected is published when Require, built with MiddlewareBuilder.Events, rejects an anonymous request. The default response is 401; ErrorResponse can override it. Every rejection publishes without deduplication, so a client controls the rate. Listeners must be cheap, and a rate limiter such as the ratelimit middleware should sit in front of Require. Requests that pass publish nothing.
Example:
unsubscribe, err := events.Listen(auth.Rejected, onRejected)
if err != nil {
return err
}
defer unsubscribe()
var UserForgotten = event.NewTopic[UserForgottenEvent]("auth.user.forgotten")
UserForgotten is emitted by UserProvider.Forget with event.Bus.Emit after every hook registered with UserProvider.OnForget succeeded, and never when a hook failed. It means "forget hooks completed": the delete may still roll back with the caller's transaction. A listener whose effect needs the delete to be committed wraps that effect in Database.AfterCommit with the event context, which carries the transaction. Emit logs listener errors instead of returning them, so listeners cannot change the outcome of Forget.
Example:
unsubscribe, err := events.Listen(auth.UserForgotten, func(ctx context.Context, forgotten auth.UserForgottenEvent) error {
return search.Remove(ctx, forgotten.Subject)
})
if err != nil {
return err
}
defer unsubscribe()
Functions ¶
func Middleware ¶ added in v0.3.0
func Middleware(authenticators ...Authenticator) router.Middleware
Middleware tries each authenticator in order and stores the first identity found in the request context. When all return ErrNoCredentials the request continues anonymously; use Require to reject it. Any other error is returned and the handler is not called.
Middleware copies the authenticator slice before returning, so replacing caller-owned entries cannot change the chain. Functions and their captured state remain shared.
Example:
r.Use(auth.Middleware( login.Authenticator(), auth.Bearer(verifyKey), ))
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"arkoren.dev/core/auth"
"arkoren.dev/core/http/router"
)
func main() {
apiKey := func(r *http.Request) (auth.Identity, error) {
if r.Header.Get("X-Demo-Key") != "secret" {
return auth.Identity{}, auth.ErrNoCredentials
}
return auth.NewIdentity("service-1"), nil
}
r := router.New()
r.Use(auth.Middleware(apiKey))
r.Get("/", func(w http.ResponseWriter, r *http.Request) error {
identity, _ := auth.FromContext(r.Context())
_, err := fmt.Fprintf(w, "subject=%q", identity.Subject())
return err
})
request := httptest.NewRequest(http.MethodGet, "/", nil)
request.Header.Set("X-Demo-Key", "secret")
response := httptest.NewRecorder()
r.ServeHTTP(response, request)
fmt.Println(response.Body.String())
}
Output: subject="service-1"
func NewContext ¶ added in v0.3.0
NewContext returns a context carrying identity. Middleware does this for requests; call it directly in tests.
Example:
ctx := auth.NewContext(context.Background(), auth.NewIdentity("42"))
identity, ok := auth.FromContext(ctx)
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
func main() {
ctx := auth.NewContext(context.Background(), auth.NewIdentity("42"))
identity, ok := auth.FromContext(ctx)
fmt.Println(identity.Subject(), ok)
}
Output: 42 true
func Require ¶ added in v0.3.0
func Require(configure ...MiddlewareBuilderFunc) router.Middleware
Require returns a middleware that rejects requests without an Identity in the context and, with MiddlewareBuilder.Events, publishes Rejected. The default is 401 with a Bearer challenge; MiddlewareBuilder.ErrorResponse can replace both the problem and its headers. A zero ErrorResponse restores the default. Rejection events omit paths and causes; the HTTP problem's normal instance rendering and request context values are unchanged.
Example:
api := r.With(auth.Require())
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"arkoren.dev/core/auth"
"arkoren.dev/core/http/router"
)
func main() {
r := router.New()
r.With(auth.Require()).Get("/", func(http.ResponseWriter, *http.Request) error { return nil })
response := httptest.NewRecorder()
r.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(response.Code, response.Header().Get("WWW-Authenticate"))
}
Output: 401 Bearer
func RequireFresh ¶ added in v0.4.0
func RequireFresh(maxAge time.Duration, configure ...MiddlewareBuilderFunc) router.Middleware
RequireFresh returns middleware that admits a request only when one of its identity's factors was verified within maxAge, so a long-lived session cannot delete an account without a recent password or second factor; Login.Confirm records such a factor. A factor with an unknown (zero) or future time is not fresh. A maxAge of zero or less admits nothing. Anonymous requests and failures are those of RequireLevel.
Example:
r.With(auth.RequireFresh(10 * time.Minute)).Delete("/account", destroy)
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"arkoren.dev/core/auth"
"arkoren.dev/core/http/router"
)
func main() {
handler := auth.RequireFresh(10 * time.Minute)(router.Handler(func(http.ResponseWriter, *http.Request) error {
return nil
}))
identity := auth.NewIdentity("1", func(principal *auth.IdentityBuilder) {
principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge, At: time.Now()})
})
r := httptest.NewRequest(http.MethodGet, "/", nil)
fmt.Println(handler(httptest.NewRecorder(), r.WithContext(auth.NewContext(r.Context(), identity))))
}
Output: <nil>
func RequireLevel ¶ added in v0.4.0
func RequireLevel(level Level, configure ...MiddlewareBuilderFunc) router.Middleware
RequireLevel returns middleware that admits a request only when its Identity has at least level (see Identity.Level). A request without an identity is rejected like Require does, with the same configuration (MiddlewareBuilder.ErrorResponse and MiddlewareBuilder.Events apply to that case only, and the callbacks run once); an identity that is too weak gets ErrStepUpRequired, for example a single-factor session on a route that needs LevelMulti. Install it after Middleware. It reads the identity from the context, so it also works for authenticators other than Login.Authenticator, such as tokens that carry factors.
Example:
r.With(auth.RequireLevel(auth.LevelMulti)).Post("/payouts", payout)
Example ¶
package main
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"arkoren.dev/core/auth"
"arkoren.dev/core/http/router"
)
func main() {
handler := auth.RequireLevel(auth.LevelMulti)(router.Handler(func(http.ResponseWriter, *http.Request) error {
return nil
}))
identity := auth.NewIdentity("1", func(principal *auth.IdentityBuilder) {
principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
})
r := httptest.NewRequest(http.MethodGet, "/", nil)
err := handler(httptest.NewRecorder(), r.WithContext(auth.NewContext(r.Context(), identity)))
fmt.Println(errors.Is(err, auth.ErrStepUpRequired))
}
Output: true
func UserFromContext ¶ added in v0.3.0
UserFromContext returns the application user of type U that the authenticator attached to the identity in ctx, by type-asserting UserRecord.Value of Identity.Record. The boolean is false when there is no identity, no record value, or the value has another type, so a mismatch fails closed.
Example:
if user, ok := auth.UserFromContext[User](r.Context()); ok {
_ = user.ID
}
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// user is the test user type.
type user struct {
Name string
}
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Record(auth.UserRecord{Subject: "42", Value: user{Name: "ann"}})
})
ctx := auth.NewContext(context.Background(), identity)
found, ok := auth.UserFromContext[user](ctx)
_, wrong := auth.UserFromContext[*user](ctx)
fmt.Println(found.Name, ok, wrong)
}
Output: ann true false
func ValidateSubject ¶
ValidateSubject returns nil when subject is 1 to 255 bytes of printable ASCII without spaces, the OpenID Connect "sub" rule minus space because some database collations ignore trailing spaces. Store subjects in a column compared bytewise. Otherwise it returns an error wrapping ErrInvalidSubject.
Example:
if err := auth.ValidateSubject("usr_9f1c"); err != nil {
return err
}
Example ¶
package main
import (
"errors"
"fmt"
"arkoren.dev/core/auth"
)
func main() {
fmt.Println(auth.ValidateSubject("usr_9f1c"))
fmt.Println(errors.Is(auth.ValidateSubject("has space"), auth.ErrInvalidSubject))
}
Output: <nil> true
Types ¶
type Authenticator ¶ added in v0.3.0
Authenticator resolves who is acting on a request. It returns ErrNoCredentials when the request has no credentials it handles, which lets the next authenticator try. Any other error stops the chain.
Only return an Identity after verifying credentials. A client-supplied identity header alone is not proof of identity.
The example uses an existing router r and your application's verifyToken function, with signature func(context.Context, string) (auth.Identity, error). The verifier must validate the token before returning an identity and return an error other than ErrNoCredentials for an invalid, expired, or revoked token. Bearer parses the header and delegates verification to that function.
Example:
authenticate := auth.Bearer(verifyToken) r.Use(auth.Middleware(authenticate), auth.Require())
Example ¶
package main
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"arkoren.dev/core/auth"
)
func main() {
var authenticate auth.Authenticator = func(r *http.Request) (auth.Identity, error) {
if r.Header.Get("X-Demo-Key") != "secret" {
return auth.Identity{}, auth.ErrNoCredentials
}
return auth.NewIdentity("service-1"), nil
}
r := httptest.NewRequest(http.MethodGet, "/", nil)
_, err := authenticate(r)
fmt.Println(errors.Is(err, auth.ErrNoCredentials))
}
Output: true
func Bearer ¶ added in v0.3.0
Bearer returns an Authenticator for "Authorization: Bearer <token>" requests. Without an Authorization header it returns ErrNoCredentials. A malformed header, or an error from verify, becomes ErrUnauthenticated with a `WWW-Authenticate: Bearer error="invalid_token"` challenge and the cause attached. If verify returns ErrNoCredentials it is passed on.
Example:
r.Use(auth.Middleware(auth.Bearer(func(ctx context.Context, token string) (auth.Identity, error) {
key, err := keys.Lookup(ctx, token)
if err != nil {
return auth.Identity{}, err
}
return auth.NewIdentity(key.OwnerSubject), nil
})))
Example ¶
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"arkoren.dev/core/auth"
)
func main() {
authenticate := auth.Bearer(func(_ context.Context, token string) (auth.Identity, error) {
if token != "good" {
return auth.Identity{}, errors.New("unknown token")
}
return auth.NewIdentity("service-1"), nil
})
request := httptest.NewRequest(http.MethodGet, "/", nil)
request.Header.Set("Authorization", "Bearer good")
identity, err := authenticate(request)
fmt.Println(identity.Subject(), err)
}
Output: service-1 <nil>
type Factor ¶ added in v0.3.0
type Factor struct {
// Method is how the factor was verified.
Method Method `json:"method"`
// Kind is what the factor proves. [Identity.Level] is derived from it.
Kind Kind `json:"kind"`
// At is when the factor was verified. The zero time means unknown.
At time.Time `json:"at"`
}
Factor records one verified proof of identity.
Example:
factor := auth.Factor{
Method: auth.MethodPassword,
Kind: auth.KindKnowledge,
At: time.Now(),
}
Example ¶
package main
import (
"fmt"
"time"
"arkoren.dev/core/auth"
)
func main() {
factor := auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession, At: time.Unix(0, 0)}
fmt.Println(factor.Method, factor.Kind)
}
Output: otp possession
type Identity ¶ added in v0.3.0
type Identity struct {
// contains filtered or unexported fields
}
Identity is who is acting: a subject, how it was authenticated and what it may do. It is an immutable value that carries no application user type, so any package can read it from a context with FromContext. Build one with NewIdentity. The zero Identity has an empty subject and no factors.
Getters return copies of slices and maps, so callers cannot change an identity after it is built.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
principal.Scopes("posts:write")
})
fmt.Println(identity.Subject(), identity.Level() == auth.LevelSingle)
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
// password, otp, hardware and federated are factors reused by the level tests.
var (
password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
otp = auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(password, otp).Scopes("posts:write")
})
fmt.Println(identity.Subject(), identity.Level() == auth.LevelMulti, identity.Scopes())
}
Output: 42 true [posts:write]
func FromContext ¶ added in v0.3.0
FromContext returns the Identity stored in ctx. The boolean reports whether one was found. It needs no knowledge of the application's user type.
Example:
if identity, ok := auth.FromContext(r.Context()); ok {
_ = identity.Subject()
}
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
func main() {
_, ok := auth.FromContext(context.Background())
fmt.Println(ok)
}
Output: false
func NewIdentity ¶ added in v0.3.0
func NewIdentity(subject string, configure ...IdentityBuilderFunc) Identity
NewIdentity publishes an immutable Identity for subject. Callbacks run once in order on one fresh draft; nil entries panic. NewIdentity does not validate subject: authenticators that take it from untrusted input should check it with ValidateSubject first.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
})
ctx := auth.NewContext(ctx, identity)
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
// password, otp, hardware and federated are factors reused by the level tests.
var password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(password)
})
fmt.Println(identity.Subject(), identity.Level() == auth.LevelSingle)
}
Output: 42 true
func (Identity) Actor ¶ added in v0.3.0
Actor returns the subject acting on behalf of the identity, or "" when the identity acts for itself.
Example:
fmt.Println(auth.NewIdentity("42").Actor() == "")
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Actor("support-7")
})
fmt.Println(identity.Actor())
}
Output: support-7
func (Identity) Factors ¶ added in v0.3.0
Factors returns a copy of the verified factors, in the order they were added.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
})
fmt.Println(len(identity.Factors()))
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
// password, otp, hardware and federated are factors reused by the level tests.
var password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(password)
})
fmt.Println(identity.Factors()[0].Method)
}
Output: pwd
func (Identity) Level ¶ added in v0.3.0
Level derives the authentication level from the factors. No factors is LevelNone. Factors of at least two distinct kinds among KindKnowledge, KindPossession and KindInherence are LevelMulti; two passwords are not. KindFederated and unknown kinds never count toward LevelMulti, so any other non-empty set of factors is LevelSingle.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(auth.Factor{Method: auth.MethodFederated, Kind: auth.KindFederated})
})
fmt.Println(identity.Level() == auth.LevelSingle)
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
// password, otp, hardware and federated are factors reused by the level tests.
var password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(password, password)
})
fmt.Println(identity.Level() == auth.LevelSingle)
}
Output: true
func (Identity) Record ¶ added in v0.3.0
func (identity Identity) Record() UserRecord
Record returns what the user provider knew about the user when the identity was built; the zero record if none was attached. The claims map is a copy.
Example:
record := auth.NewIdentity("42").Record()
fmt.Println(record.Value == nil)
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Record(auth.UserRecord{Subject: "42", Version: "v1"})
})
fmt.Println(identity.Record().Version)
}
Output: v1
func (Identity) Scopes ¶ added in v0.3.0
Scopes returns a copy of the granted scopes.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Scopes("read")
})
fmt.Println(identity.Scopes())
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Scopes("read")
})
fmt.Println(identity.Scopes())
}
Output: [read]
type IdentityBuilder ¶ added in v0.3.0
type IdentityBuilder struct {
// contains filtered or unexported fields
}
IdentityBuilder configures NewIdentity before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft, and retaining it cannot change a published identity.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Scopes("read").Actor("support-7")
})
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Scopes("read").Actor("support-7")
})
fmt.Println(identity.Scopes(), identity.Actor())
}
Output: [read] support-7
func (*IdentityBuilder) Actor ¶ added in v0.3.0
func (principal *IdentityBuilder) Actor(actor string) *IdentityBuilder
Actor sets the subject acting on behalf of the identity, for example a support agent impersonating a user. The default, empty, means the identity acts for itself. The setting replaces the previous value on this draft.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Actor("support-7")
})
fmt.Println(identity.Actor())
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Actor("support-7")
})
fmt.Println(identity.Actor())
}
Output: support-7
func (*IdentityBuilder) Factors ¶ added in v0.3.0
func (principal *IdentityBuilder) Factors(factors ...Factor) *IdentityBuilder
Factors appends verified factors. The slice is copied, so later edits by the caller do not change the identity.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(
auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge},
auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession},
)
})
fmt.Println(identity.Level() == auth.LevelMulti)
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
// password, otp, hardware and federated are factors reused by the level tests.
var (
password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
otp = auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Factors(password, otp)
})
fmt.Println(identity.Level() == auth.LevelMulti)
}
Output: true
func (*IdentityBuilder) Record ¶ added in v0.3.0
func (principal *IdentityBuilder) Record(record UserRecord) *IdentityBuilder
Record attaches what the user provider knows about the user, including the application's own user in UserRecord.Value, which UserFromContext and gate rules read. The claims map is copied. The setting replaces the previous value on this draft.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Record(auth.UserRecord{Subject: "42", Value: User{ID: 42}})
})
fmt.Println(identity.Record().Subject)
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Record(auth.UserRecord{Subject: "42", Value: "ann"})
})
fmt.Println(identity.Record().Value)
}
Output: ann
func (*IdentityBuilder) Scopes ¶ added in v0.3.0
func (principal *IdentityBuilder) Scopes(scopes ...string) *IdentityBuilder
Scopes appends granted scopes. The slice is copied, so later edits by the caller do not change the identity. Scopes are opaque strings; use gate.HasScopes to require them.
Example:
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Scopes("posts:read", "posts:write")
})
fmt.Println(identity.Scopes())
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
principal.Scopes("posts:read", "posts:write")
})
fmt.Println(identity.Scopes())
}
Output: [posts:read posts:write]
type IdentityBuilderFunc ¶ added in v0.3.0
type IdentityBuilderFunc = func(*IdentityBuilder)
IdentityBuilderFunc configures an IdentityBuilder.
Example:
var policy auth.IdentityBuilderFunc = func(principal *auth.IdentityBuilder) {
principal.Scopes("read")
}
identity := auth.NewIdentity("42", policy)
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
policy := auth.IdentityBuilderFunc(func(principal *auth.IdentityBuilder) {
principal.Scopes("read")
})
fmt.Println(auth.NewIdentity("42", policy).Scopes())
}
Output: [read]
type Kind ¶ added in v0.3.0
type Kind string
Kind classifies what a Factor proves, following the usual three authentication categories plus an externally asserted one. The values are our own strings.
Identity.Level counts distinct kinds: two different kinds among KindKnowledge, KindPossession and KindInherence make a multi-factor identity. KindFederated never counts toward that, because it only reports that another provider authenticated the user.
Example:
factor := auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
fmt.Println(auth.KindKnowledge, auth.KindPossession, auth.KindInherence, auth.KindFederated)
}
Output: knowledge possession inherence federated
const ( // KindKnowledge is something the user knows, such as a password. KindKnowledge Kind = "knowledge" // KindPossession is something the user has, such as a hardware key. KindPossession Kind = "possession" // KindInherence is something the user is, such as a fingerprint. KindInherence Kind = "inherence" // KindFederated marks an authentication performed by an external identity // provider. It never contributes to [LevelMulti], however many federated // factors an identity has, because Arkoren cannot see which factors the // provider required. KindFederated Kind = "federated" )
type Level ¶ added in v0.3.0
type Level int
Level summarizes how strongly an Identity was authenticated. It is derived from the identity's factors by Identity.Level, never set directly.
Example:
identity := auth.NewIdentity("42")
if identity.Level() < auth.LevelSingle {
return auth.ErrUnauthenticated
}
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
// password, otp, hardware and federated are factors reused by the level tests.
var (
password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
otp = auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}
)
// levelOf builds an identity with factors and returns its level.
func levelOf(factors ...auth.Factor) auth.Level {
return auth.NewIdentity("1", func(principal *auth.IdentityBuilder) {
principal.Factors(factors...)
}).Level()
}
func main() {
fmt.Println(levelOf() == auth.LevelNone, levelOf(password) == auth.LevelSingle, levelOf(password, otp) == auth.LevelMulti)
}
Output: true true true
const ( // LevelNone means the identity has no factors. LevelNone Level = iota // LevelSingle means the identity has factors, but not two distinct // knowledge, possession or inherence kinds. LevelSingle // LevelMulti means the identity has factors of at least two distinct kinds // among [KindKnowledge], [KindPossession] and [KindInherence]. LevelMulti )
type Login ¶ added in v0.4.0
type Login struct {
// contains filtered or unexported fields
}
Login turns "this person proved X" into a logged-in browser session. Every login method (password, OAuth, SAML, passkey) calls Login.Begin after it verified its credential. Begin either logs the user in or, when a registered second-factor check says the user needs one, parks the login in a pending state in which the request stays anonymous until Login.Complete. The factors recorded along the way give Identity.Level, and RequireLevel and RequireFresh guard routes with them.
A Login stores one session record (subject, factors, credential version and a login-record ID) under one session key and a pending login under a second, so a login can never be half written. Every transition (Begin, Complete, Fail, Confirm, Logout) regenerates the session ID, which prevents session fixation.
All methods read the session from the request context with the handle chosen by LoginBuilder.Handle, so session.Middleware must run first; without a session they return session.ErrNoSession (the authenticator returns ErrNoCredentials). Methods change the session in memory; it is saved by the session middleware, so change it before the response headers are written. Concurrent use is safe: a Login is immutable after construction.
Create one with NewLogin. In an application the build order is user provider, arks, NewLogin, handlers.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.SecondFactor(factors.Enrolled)
})
if err != nil {
return err
}
r.Use(session.Middleware(store), auth.Middleware(login.Authenticator()))
Example ¶
login := exampleLogin()
r := exampleRequest()
complete, err := login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
identity, _ := login.Authenticator()(r)
fmt.Println(complete, err, identity.Subject(), identity.Level() == auth.LevelSingle)
Output: true <nil> 1 true
func NewLogin ¶ added in v0.4.0
func NewLogin(provider *UserProvider, store *cache.Cache, configure ...LoginBuilderFunc) (*Login, error)
NewLogin returns a Login over provider. store is the cache the application also gives to session.Middleware; it keeps each user's login records (see Login.Logins). NewLogin registers Login.RevokeAll with UserProvider.OnForget, so forgetting a user ends their sessions. It returns an error when provider or store is nil, when LoginBuilder.ChallengeTTL, LoginBuilder.MaxAttempts, LoginBuilder.MaxLogins or LoginBuilder.SessionLifetime is not positive, or when a second-factor check or LoginBuilder.ClientIP is nil. Construction does no I/O and the callbacks run once, in order.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.ChallengeTTL(10 * time.Minute)
policy.SecondFactor(factors.Enrolled)
})
Example ¶
package main
import (
"context"
"fmt"
"time"
"arkoren.dev/core/auth"
"arkoren.dev/core/service/cache"
"arkoren.dev/core/service/cache/memorycache"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
users, err := auth.NewUserProvider(exampleDriver())
if err != nil {
panic(err)
}
login, err := auth.NewLogin(users, cache.New(memorycache.New()), func(policy *auth.LoginBuilder) {
policy.ChallengeTTL(10 * time.Minute)
})
fmt.Println(login != nil, err)
}
Output: true <nil>
func (*Login) Authenticator ¶ added in v0.4.0
func (login *Login) Authenticator() Authenticator
Authenticator returns the Authenticator to pass to Middleware. It reads only the logged-in session record, never a pending login, so a half-logged-in request stays anonymous. It looks the subject up with the provider on every request and builds an Identity carrying the stored factors and the provider's UserRecord, so UserFromContext returns its Value.
A missing session, an absent or unreadable record, a deleted or disabled user (ErrUserNotFound, ErrUserDisabled), a credential version that no longer matches UserRecord.Version and a login record that was revoked, expired or dropped (see Login.Revoke) all return ErrNoCredentials, which makes the request anonymous. The version comparison is constant time. Other provider errors and errors reading the login records from the store pass through and stop the chain. The check costs one cache read per request; when the record's SeenAt is older than five minutes the authenticator also tries to refresh it, ignoring a failed write.
Example:
r.Use(session.Middleware(store), auth.Middleware(login.Authenticator()))
Example ¶
login := exampleLogin()
r := exampleRequest()
_, _ = login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
handler := auth.Middleware(login.Authenticator())(func(_ http.ResponseWriter, r *http.Request) error {
user, _ := auth.UserFromContext[exampleUser](r.Context())
fmt.Println(user.Role)
return nil
})
_ = handler(httptest.NewRecorder(), r)
Output: admin
func (*Login) Begin ¶ added in v0.4.0
func (login *Login) Begin(r *http.Request, subject string, factor Factor) (complete bool, err error)
Begin is the single entry for every login method. Call it after the method verified its credential, passing the verified factor; a zero factor.At means now. It first looks subject up with the provider: a deleted or disabled user is ErrUnauthenticated, and other provider errors, including ErrInvalidSubject, are returned unchanged.
It then asks each LoginBuilder.SecondFactor check. When none says yes it logs the user in with factor, regenerates the session ID and returns true. Otherwise it replaces any logged-in user with a pending login that expires after LoginBuilder.ChallengeTTL, regenerates the session ID and returns false: the request stays anonymous until Login.Complete. The caller then asks for the second factor. A check error fails the login with that error and changes nothing.
Logging in creates a LoginRecord for the device (see Login.Logins) and removes the record of the login the session replaces, so Begin can also return the cache or lock errors of the record store; the session is then unchanged. A login that is parked creates its record at Login.Complete.
Begin does not verify the credential: call it only after it checked out.
Example:
complete, err := login.Begin(r, subject, auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
if err != nil {
return err
}
if !complete {
return response.Status(w, http.StatusAccepted) // Ask for the second factor.
}
Example ¶
login := exampleLogin()
r := exampleRequest()
complete, err := login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(complete, err)
_, err = login.Begin(r, "2", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(errors.Is(err, auth.ErrUnauthenticated))
Output: true <nil> true
func (*Login) Complete ¶ added in v0.4.0
Complete finishes a pending login after the second factor verified: it logs the user in with the factors verified at Login.Begin plus factor (a zero factor.At means now), creates the LoginRecord of the device as Login.Begin does, regenerates the session ID and consumes the pending login, so a second call returns ErrUnauthenticated. The errors are those of Login.Pending plus the cache and lock errors of the record store; on any error nothing is logged in.
Complete does not verify the factor: call it only after it checked out.
Example:
if _, err := login.Pending(r); err != nil {
return err
}
if !verifyCode(code) {
return login.Fail(r)
}
return login.Complete(r, auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession})
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.SecondFactor(needsSecondFactor)
})
r := exampleRequest()
_, _ = login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
err := login.Complete(r, auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession})
identity, _ := login.Authenticator()(r)
fmt.Println(err, identity.Level() == auth.LevelMulti)
Output: <nil> true
func (*Login) Confirm ¶ added in v0.4.0
Confirm records a freshly verified factor on the logged-in session and regenerates the session ID. Use it to re-check a password before a sensitive change, which satisfies RequireFresh, or to add a second factor later so RequireLevel passes. A factor with the same Method as a recorded one replaces it, so each method appears once with its latest time; a zero factor.At means now. It returns ErrUnauthenticated when the session holds no logged-in user.
Confirm does not verify the factor: call it only after it checked out.
Example:
if err := login.Confirm(r, auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}); err != nil {
return err
}
Example ¶
login := exampleLogin()
r := exampleRequest()
_, _ = login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
err := login.Confirm(r, auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession})
identity, _ := login.Authenticator()(r)
fmt.Println(err, len(identity.Factors()))
Output: <nil> 2
func (*Login) Fail ¶ added in v0.4.0
Fail counts one wrong second-factor attempt on the pending login and regenerates the session ID. When the count reaches LoginBuilder.MaxAttempts the pending login is discarded and the next Login.Pending returns ErrUnauthenticated. It returns ErrUnauthenticated when there is no pending login. The count lives in the session, so it limits one browser session only; rate-limit by user or address as well.
Example:
if !verifyCode(code) {
if err := login.Fail(r); err != nil {
return err
}
return problem.Unauthorized()
}
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.SecondFactor(needsSecondFactor)
policy.MaxAttempts(1)
})
r := exampleRequest()
_, _ = login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(login.Fail(r))
_, err := login.Pending(r)
fmt.Println(errors.Is(err, auth.ErrUnauthenticated))
Output: <nil> true
func (*Login) Logins ¶ added in v0.5.0
func (login *Login) Logins(r *http.Request) ([]LoginRecord, error)
Logins returns the login records of the request's user, oldest first, with LoginRecord.Current set on the record of this request's own login. It returns ErrUnauthenticated when the session holds no logged-in user or its own login was revoked, and session.ErrNoSession without a session. Mount it behind Require.
Example:
records, err := login.Logins(r)
if err != nil {
return err
}
return response.JSON(w, http.StatusOK, records)
Example ¶
login := exampleLogin() first := exampleRequest() _, _ = login.Begin(first, "1", examplePassword) _, _ = login.Begin(exampleRequest(), "1", examplePassword) records, _ := login.Logins(first) fmt.Println(len(records), records[0].Current, records[1].Current)
Output: 2 true false
func (*Login) LoginsOf ¶ added in v0.5.0
LoginsOf returns the login records of subject, oldest first, for administration. It returns an error wrapping ErrInvalidSubject for an invalid subject and no records, not an error, for a user without logins. The records are personal data.
Example:
records, err := login.LoginsOf(ctx, subject)
if err != nil {
return err
}
fmt.Println(len(records), "devices")
Example ¶
login := exampleLogin() _, _ = login.Begin(exampleRequest(), "1", examplePassword) records, err := login.LoginsOf(context.Background(), "1") fmt.Println(len(records), err)
Output: 1 <nil>
func (*Login) Logout ¶ added in v0.4.0
Logout removes the logged-in session record, its login record and any pending login, even stale or unreadable ones, and regenerates the session ID. Other session data and its lifetime stay; use session.Session.Destroy to remove the whole session.
Example:
if err := login.Logout(r); err != nil {
return err
}
Example ¶
login := exampleLogin()
r := exampleRequest()
_, _ = login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(login.Logout(r))
_, err := login.Authenticator()(r)
fmt.Println(errors.Is(err, auth.ErrNoCredentials))
Output: <nil> true
func (*Login) Pending ¶ added in v0.4.0
func (login *Login) Pending(r *http.Request) (UserRecord, error)
Pending returns the user waiting for a second factor, as parked by Login.Begin. It returns ErrUnauthenticated when there is no pending login, it expired (which also clears it) or the user was deleted, disabled or had its UserRecord.Version changed, for example by a password change, in the meantime (which discards it). Other provider errors pass through. Pending does not consume the login, so a handler can read the user, check a code and report a wrong one with Login.Fail.
Example:
user, err := login.Pending(r)
if err != nil {
return err
}
ok := verifyCode(user.Subject, code)
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.SecondFactor(needsSecondFactor)
})
r := exampleRequest()
_, _ = login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
user, err := login.Pending(r)
fmt.Println(user.Subject, err)
Output: 1 <nil>
func (*Login) Revoke ¶ added in v0.5.0
Revoke logs the devices with the given record IDs out: each device's next request is anonymous, because the authenticator no longer finds its record. Unknown IDs are ignored, so it is idempotent. It returns an error wrapping ErrInvalidSubject for an invalid subject, and cache or lock errors; after an error nothing is guaranteed to have been revoked, so retry.
Example:
if err := login.Revoke(r.Context(), subject, r.PathValue("id")); err != nil {
return err
}
Example ¶
login := exampleLogin() r := exampleRequest() _, _ = login.Begin(r, "1", examplePassword) records, _ := login.Logins(r) fmt.Println(login.Revoke(context.Background(), "1", records[0].ID)) _, err := login.Authenticator()(r) fmt.Println(errors.Is(err, auth.ErrNoCredentials))
Output: <nil> true
func (*Login) RevokeAll ¶ added in v0.5.0
RevokeAll logs every device of subject out by deleting the subject's record list. It returns an error wrapping ErrInvalidSubject for an invalid subject. NewLogin registers it with UserProvider.OnForget, so forgetting a user ends their sessions.
Example:
if err := login.RevokeAll(ctx, subject); err != nil {
return err
}
Example ¶
login := exampleLogin() r := exampleRequest() _, _ = login.Begin(r, "1", examplePassword) fmt.Println(login.RevokeAll(context.Background(), "1")) records, _ := login.LoginsOf(context.Background(), "1") fmt.Println(len(records))
Output: <nil> 0
func (*Login) RevokeOthers ¶ added in v0.5.0
RevokeOthers logs every device of the request's user out except the one that made the request. It returns ErrUnauthenticated when the session holds no logged-in user or its own login was revoked (nothing is revoked then), and session.ErrNoSession without a session.
Example:
if err := login.RevokeOthers(r); err != nil {
return err
}
Example ¶
login := exampleLogin() mine, other := exampleRequest(), exampleRequest() _, _ = login.Begin(mine, "1", examplePassword) _, _ = login.Begin(other, "1", examplePassword) fmt.Println(login.RevokeOthers(mine)) _, err := login.Authenticator()(other) fmt.Println(errors.Is(err, auth.ErrNoCredentials))
Output: <nil> true
type LoginBuilder ¶ added in v0.4.0
type LoginBuilder struct {
// contains filtered or unexported fields
}
LoginBuilder configures NewLogin before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic. Methods return the same draft, and retaining it cannot change a published login.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.ChallengeTTL(10 * time.Minute).MaxAttempts(3)
})
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.ChallengeTTL(time.Minute).MaxAttempts(3).SecondFactor(needsSecondFactor)
})
complete, err := login.Begin(exampleRequest(), "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(complete, err)
Output: false <nil>
func (*LoginBuilder) ChallengeTTL ¶ added in v0.4.0
func (policy *LoginBuilder) ChallengeTTL(ttl time.Duration) *LoginBuilder
ChallengeTTL sets how long a pending login (see Login.Begin) accepts its second factor. The default is five minutes. NewLogin rejects a value of zero or less. The setting replaces the previous value on this draft.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.ChallengeTTL(10 * time.Minute)
})
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.SecondFactor(needsSecondFactor).ChallengeTTL(10 * time.Minute)
})
r := exampleRequest()
complete, err := login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(complete, err)
Output: false <nil>
func (*LoginBuilder) ClientIP ¶ added in v0.5.0
func (policy *LoginBuilder) ClientIP(find func(*http.Request) string) *LoginBuilder
ClientIP sets how the address of a login record is found. The default is the host of r.RemoteAddr, which behind a reverse proxy is the proxy. Behind a proxy, pass a function that trusts forwarded headers only from your proxies: ratelimit.TrustedProxyKey (package core/http/middleware/ratelimit) returns such a function. It reports IPv4 addresses as they are but reduces IPv6 addresses to their /64 prefix, which is what the record then stores. The result is cut to 255 bytes. NewLogin rejects nil. The setting replaces the previous value on this draft.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.ClientIP(ratelimit.TrustedProxyKey(netip.MustParsePrefix("10.0.0.0/8")))
})
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.ClientIP(ratelimit.TrustedProxyKey(netip.MustParsePrefix("10.0.0.0/8")))
})
r := exampleRequest()
r.RemoteAddr = "10.0.0.1:4711"
r.Header.Set("X-Forwarded-For", "198.51.100.2")
_, _ = login.Begin(r, "1", examplePassword)
records, _ := login.Logins(r)
fmt.Println(records[0].IP)
Output: 198.51.100.2
func (*LoginBuilder) Devices ¶ added in v0.5.0
func (policy *LoginBuilder) Devices(enabled bool) *LoginBuilder
Devices selects whether login records keep the User-Agent and client address of each login, which is what makes the device list readable. The default is true. With false the records hold only IDs and times. Both values are personal data; they are never put in telemetry or events. The setting replaces the previous value on this draft.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.Devices(false)
})
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.Devices(false)
})
r := exampleRequest()
r.Header.Set("User-Agent", "Firefox")
_, _ = login.Begin(r, "1", examplePassword)
records, _ := login.Logins(r)
fmt.Printf("%q\n", records[0].UserAgent)
Output: ""
func (*LoginBuilder) Handle ¶ added in v0.4.0
func (policy *LoginBuilder) Handle(handle session.Handle) *LoginBuilder
Handle selects the request session bridge shared with session.Middleware, so one application can run several independent sessions. Zero, the default, selects the default bridge. It changes neither cookie nor storage policy. The setting replaces the previous value on this draft.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.Handle(adminSession)
})
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"time"
"arkoren.dev/core/auth"
"arkoren.dev/core/http/session"
"arkoren.dev/core/service/cache"
"arkoren.dev/core/service/cache/memorycache"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
// exampleLogin returns a login over exampleDriver; policy callbacks configure it.
func exampleLogin(configure ...auth.LoginBuilderFunc) *auth.Login {
users, err := auth.NewUserProvider(exampleDriver())
if err != nil {
panic(err)
}
login, err := auth.NewLogin(users, cache.New(memorycache.New()), configure...)
if err != nil {
panic(err)
}
return login
}
func main() {
handle := session.NewHandle()
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.Handle(handle)
})
r := httptest.NewRequest(http.MethodGet, "/", nil)
r = r.WithContext(session.NewContextFor(r.Context(), handle, session.New(time.Now().Add(time.Hour), map[string]any{})))
complete, err := login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(complete, err)
}
Output: true <nil>
func (*LoginBuilder) MaxAttempts ¶ added in v0.4.0
func (policy *LoginBuilder) MaxAttempts(attempts int) *LoginBuilder
MaxAttempts sets how many calls to Login.Fail discard a pending login. The default is five. NewLogin rejects a value of zero or less. The setting replaces the previous value on this draft.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.MaxAttempts(3)
})
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.SecondFactor(needsSecondFactor).MaxAttempts(2)
})
r := exampleRequest()
_, _ = login.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
_ = login.Fail(r)
_, err := login.Pending(r)
fmt.Println(err)
_ = login.Fail(r)
_, err = login.Pending(r)
fmt.Println(errors.Is(err, auth.ErrUnauthenticated))
Output: <nil> true
func (*LoginBuilder) MaxLogins ¶ added in v0.5.0
func (policy *LoginBuilder) MaxLogins(limit int) *LoginBuilder
MaxLogins sets how many login records one user keeps. The default is 50. A new login beyond it drops the oldest record, which logs that device out. NewLogin rejects a value of zero or less. The setting replaces the previous value on this draft.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.MaxLogins(10)
})
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.MaxLogins(1)
})
first, second := exampleRequest(), exampleRequest()
_, _ = login.Begin(first, "1", examplePassword)
_, _ = login.Begin(second, "1", examplePassword)
_, err := login.Authenticator()(first)
fmt.Println(errors.Is(err, auth.ErrNoCredentials))
Output: true
func (*LoginBuilder) SecondFactor ¶ added in v0.4.0
func (policy *LoginBuilder) SecondFactor(check func(ctx context.Context, subject string) (bool, error)) *LoginBuilder
SecondFactor registers a check that reports whether subject must present a second factor before Login.Begin logs them in, for example an "is two-factor enrolled" lookup of an ark. Core receives plain functions, so it never imports the package that owns the answer. It may be called several times: one yes from any check is enough to require a second factor, and the first error stops the login and is returned by Begin. A nil check makes NewLogin fail.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.SecondFactor(factors.Enrolled)
})
Example ¶
enrolled := map[string]bool{"1": true}
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.SecondFactor(func(_ context.Context, subject string) (bool, error) {
return enrolled[subject], nil
})
})
complete, err := login.Begin(exampleRequest(), "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(complete, err)
Output: false <nil>
func (*LoginBuilder) SessionLifetime ¶ added in v0.5.0
func (policy *LoginBuilder) SessionLifetime(lifetime time.Duration) *LoginBuilder
SessionLifetime tells the login the maximum session lifetime configured on session.Middleware with session.Builder.MaxLifetime, which the session package does not expose to other packages. A user's list of login records lives that long after its last write, and a record older than it is never listed and is removed by the next write, so no record outlives its sessions. The default is session.DefaultMaxLifetime; set it when the middleware uses another value. NewLogin rejects a value of zero or less. The setting replaces the previous value on this draft.
Example:
login, err := auth.NewLogin(users, store, func(policy *auth.LoginBuilder) {
policy.SessionLifetime(7 * 24 * time.Hour)
})
Example ¶
login := exampleLogin(func(policy *auth.LoginBuilder) {
policy.SessionLifetime(7 * 24 * time.Hour)
})
complete, err := login.Begin(exampleRequest(), "1", examplePassword)
fmt.Println(complete, err)
Output: true <nil>
type LoginBuilderFunc ¶ added in v0.4.0
type LoginBuilderFunc = func(*LoginBuilder)
LoginBuilderFunc configures a LoginBuilder.
Example:
policy := auth.LoginBuilderFunc(func(policy *auth.LoginBuilder) {
policy.MaxAttempts(3)
})
login, err := auth.NewLogin(users, store, policy)
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
"arkoren.dev/core/service/cache"
"arkoren.dev/core/service/cache/memorycache"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
// exampleLogin returns a login over exampleDriver; policy callbacks configure it.
func exampleLogin(configure ...auth.LoginBuilderFunc) *auth.Login {
users, err := auth.NewUserProvider(exampleDriver())
if err != nil {
panic(err)
}
login, err := auth.NewLogin(users, cache.New(memorycache.New()), configure...)
if err != nil {
panic(err)
}
return login
}
func main() {
policy := auth.LoginBuilderFunc(func(policy *auth.LoginBuilder) {
policy.MaxAttempts(3)
})
fmt.Println(exampleLogin(policy) != nil)
}
Output: true
type LoginRecord ¶ added in v0.5.0
type LoginRecord struct {
// ID identifies the login. It is random, stays the same when the session ID
// rotates and is what [Login.Revoke] takes.
ID string `json:"id"`
// CreatedAt is when the user logged in, in UTC.
CreatedAt time.Time `json:"created_at"`
// SeenAt is when the login last authenticated a request, in UTC. It is
// refreshed at most once per five minutes and on a best-effort basis, so it
// can lag by that much or more.
SeenAt time.Time `json:"seen_at"`
// UserAgent is the User-Agent request header at login, truncated to 255
// bytes. It is empty when [LoginBuilder.Devices] is false.
UserAgent string `json:"user_agent,omitzero"`
// IP is the client address at login, from [LoginBuilder.ClientIP], cut to 255
// bytes. It is empty when [LoginBuilder.Devices] is false.
IP string `json:"ip,omitzero"`
// Current is true for the record of the request's own login. Only
// [Login.Logins] sets it; it is never stored, so it appears in JSON only
// when true.
Current bool `json:"current,omitzero"`
}
LoginRecord is one login of one user on one device, as listed by Login.Logins and Login.LoginsOf. It holds personal data (user agent and address): show it to its owner and administrators only, and never put it in telemetry or events.
Example:
records, err := login.Logins(r)
if err != nil {
return err
}
for _, record := range records {
fmt.Println(record.UserAgent, record.IP, record.SeenAt, record.Current)
}
Example ¶
login := exampleLogin()
r := exampleRequest()
r.Header.Set("User-Agent", "Firefox")
r.RemoteAddr = "203.0.113.7:4711"
_, _ = login.Begin(r, "1", examplePassword)
records, _ := login.Logins(r)
fmt.Println(records[0].UserAgent, records[0].IP, records[0].Current)
Output: Firefox 203.0.113.7 true
type Method ¶ added in v0.3.0
type Method string
Method names how a Factor was verified. The values "pwd", "otp", "hwk" and "swk" are the Authentication Method Reference values of RFC 8176; MethodRecovery and MethodFederated are Arkoren's own values, which RFC 8176 does not define. Applications may use further strings.
Example:
factor := auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
fmt.Println(auth.MethodPassword, auth.MethodOTP, auth.MethodHardwareKey, auth.MethodSoftwareKey, auth.MethodRecovery, auth.MethodFederated)
}
Output: pwd otp hwk swk recovery federated
const ( // MethodPassword is a password check ("pwd", RFC 8176). MethodPassword Method = "pwd" // MethodOTP is a one-time password such as TOTP ("otp", RFC 8176). MethodOTP Method = "otp" // MethodHardwareKey is proof of possession of a hardware-secured key // ("hwk", RFC 8176). MethodHardwareKey Method = "hwk" // MethodSoftwareKey is proof of possession of a software-stored key // ("swk", RFC 8176). MethodSoftwareKey Method = "swk" // MethodRecovery is a single-use recovery code. It is an Arkoren value, not // an RFC 8176 one. MethodRecovery Method = "recovery" // MethodFederated is authentication by an external identity provider. It is // an Arkoren value, not an RFC 8176 one. MethodFederated Method = "federated" )
type MiddlewareBuilder ¶ added in v0.3.0
type MiddlewareBuilder struct {
// contains filtered or unexported fields
}
MiddlewareBuilder configures Require before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic. Retaining the draft cannot change published settings. Methods return the same draft.
Example:
r := router.New()
r.Use(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
authenticator.ErrorResponse(problem.Unauthorized("Bearer"))
}))
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
"arkoren.dev/foundation/problem"
)
func main() {
middleware := auth.Require(func(authenticator *auth.MiddlewareBuilder) {
authenticator.ErrorResponse(problem.Unauthorized("Basic"))
})
fmt.Println(middleware != nil)
}
Output: true
func (*MiddlewareBuilder) ErrorResponse ¶ added in v0.3.0
func (authenticator *MiddlewareBuilder) ErrorResponse(response problem.Details) *MiddlewareBuilder
ErrorResponse is the problem returned for anonymous requests. Zero uses ErrUnauthenticated with a "WWW-Authenticate: Bearer" challenge.
The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.
Example:
r := router.New()
r.Use(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
authenticator.ErrorResponse(problem.Forbidden())
}))
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"arkoren.dev/core/auth"
"arkoren.dev/core/http/router"
"arkoren.dev/foundation/problem"
)
func main() {
r := router.New()
r.With(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
authenticator.ErrorResponse(problem.Unauthorized("Basic"))
})).Get("/", func(http.ResponseWriter, *http.Request) error { return nil })
response := httptest.NewRecorder()
r.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(response.Header().Get("WWW-Authenticate"))
}
Output: Basic
func (*MiddlewareBuilder) Events ¶ added in v0.3.0
func (authenticator *MiddlewareBuilder) Events(bus *event.Bus) *MiddlewareBuilder
Events receives Rejected when Require rejects a request. The default, nil, publishes nothing.
The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.
Example:
r := router.New()
r.Use(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
authenticator.Events(event.New())
}))
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"arkoren.dev/core/auth"
"arkoren.dev/core/event"
"arkoren.dev/core/http/router"
)
func main() {
bus := event.New()
_, _ = bus.Listen(auth.Rejected, func(_ context.Context, rejected auth.RejectedEvent) error {
fmt.Println("rejected", rejected.Method)
return nil
})
r := router.New()
r.With(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
authenticator.Events(bus)
})).Get("/", func(http.ResponseWriter, *http.Request) error { return nil })
r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
}
Output: rejected GET
type MiddlewareBuilderFunc ¶ added in v0.3.0
type MiddlewareBuilderFunc = func(*MiddlewareBuilder)
MiddlewareBuilderFunc edits one Require draft synchronously. Callbacks run directly once in order; nil entries panic and expanded nil/empty slices omit edits. The completed settings detach from the draft, not event services or captures.
Example:
var policy auth.MiddlewareBuilderFunc = func(authenticator *auth.MiddlewareBuilder) {
authenticator.Events(events)
}
r.Use(auth.Require(policy))
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
"arkoren.dev/foundation/problem"
)
func main() {
policy := auth.MiddlewareBuilderFunc(func(authenticator *auth.MiddlewareBuilder) {
authenticator.ErrorResponse(problem.Forbidden())
})
fmt.Println(auth.Require(policy) != nil)
}
Output: true
type RejectedEvent ¶ added in v0.3.0
type RejectedEvent struct {
// Method is the client-controlled HTTP method, not a route or user identity.
// Applications must not place secrets in custom method names.
//
// Example:
// logger.InfoContext(ctx, "authentication required", "method", rejected.Method)
Method string
}
RejectedEvent reports anonymous rejection without request paths, which can contain identifiers or credentials. It carries no user, credential, header, query, or cause. Its event context still contains the request's context values.
Example:
unsubscribe, err := events.Listen(auth.Rejected, func(ctx context.Context, rejected auth.RejectedEvent) error {
logger.InfoContext(ctx, "authentication required", "method", rejected.Method)
return nil
})
if err != nil {
return err
}
defer unsubscribe()
Example ¶
package main
import (
"fmt"
"net/http"
"arkoren.dev/core/auth"
)
func main() {
fmt.Println(auth.RejectedEvent{Method: http.MethodGet}.Method)
}
Output: GET
type TypedUserDriver ¶
type TypedUserDriver[K comparable, U any] struct { // contains filtered or unexported fields }
TypedUserDriver is a UserDriver that adapts an application's typed loader. It converts subjects to the identifier type K, loads the user U, and builds the UserRecord from it. Create it with NewUserDriver.
Example:
driver, err := auth.NewUserDriver(loadUser, func(user User) int64 { return user.ID })
subject, err := driver.Subject(User{ID: 42}) // "42"
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
driver := exampleDriver()
record, err := driver.Find(context.Background(), "1")
fmt.Println(record.Value.(exampleUser).Role, err)
}
Output: admin <nil>
func NewUserDriver ¶
func NewUserDriver[K comparable, U any]( load func(context.Context, K) (U, error), id func(U) K, configure ...UserDriverBuilderFunc[U], ) (*TypedUserDriver[K, U], error)
NewUserDriver returns a TypedUserDriver that loads users with load and identifies them with id. K must be a string kind, an integer kind, or a type implementing both encoding.TextMarshaler and (through its pointer) encoding.TextUnmarshaler, such as UUID, xid and ULID types; any other K fails with an error wrapping ErrInvalidSubject so the mistake surfaces at setup. It also fails for a nil load or id. Construction callbacks configure UserDriverBuilder.
load reports a deleted user with ErrUserNotFound (or an error wrapping it); returning a nil pointer with a nil error counts as not found too. Other loader errors pass through unchanged.
Example:
driver, err := auth.NewUserDriver(
func(ctx context.Context, id int64) (User, error) { return store.User(ctx, id) },
func(user User) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[User]) {
driver.Disabled(func(user User) bool { return user.Suspended })
},
)
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
func main() {
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
func(user exampleUser) int64 { return user.ID },
)
if err != nil {
panic(err)
}
record, _ := driver.Find(context.Background(), "9")
fmt.Println(record.Subject)
}
Output: 9
func (*TypedUserDriver[K, U]) Find ¶
func (driver *TypedUserDriver[K, U]) Find(ctx context.Context, subject string) (UserRecord, error)
Find implements UserDriver. It parses subject canonically (an error wrapping ErrInvalidSubject otherwise, never ErrUserNotFound), calls the loader, and returns ErrUserNotFound for a nil pointer with a nil error and ErrUserDisabled when the Disabled function reports the user. The record's Value is the loaded U.
Example:
record, err := driver.Find(ctx, "42")
if err != nil {
return err
}
user := record.Value.(User)
Example ¶
package main
import (
"context"
"errors"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
_, err := exampleDriver().Find(context.Background(), "+1")
fmt.Println(errors.Is(err, auth.ErrInvalidSubject))
}
Output: true
func (*TypedUserDriver[K, U]) Subject ¶
func (driver *TypedUserDriver[K, U]) Subject(user U) (string, error)
Subject returns the subject of user, derived from the identifier function. It returns an error wrapping ErrInvalidSubject when the identifier does not render to a valid subject, such as an empty string.
Example:
subject, err := driver.Subject(user)
if err != nil {
return err
}
err = users.Forget(ctx, subject)
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
subject, err := exampleDriver().Subject(exampleUser{ID: 42})
fmt.Println(subject, err)
}
Output: 42 <nil>
type UserDriver ¶
type UserDriver interface {
// Find returns the record of subject.
//
// Example:
//
// record, err := driver.Find(ctx, "42")
Find(ctx context.Context, subject string) (UserRecord, error)
}
UserDriver finds users by subject. Implementations must return an error wrapping ErrInvalidSubject for a subject that fails ValidateSubject, ErrUserNotFound for a missing user and ErrUserDisabled for a disabled one, with the record's Subject set to the argument. They must be safe for concurrent use. The conformance suite is arkoren.dev/core/auth/authtest.
Example:
type directory struct{}
func (directory) Find(ctx context.Context, subject string) (auth.UserRecord, error) {
return auth.UserRecord{}, auth.ErrUserNotFound
}
Example ¶
package main
import (
"context"
"errors"
"fmt"
"arkoren.dev/core/auth"
"arkoren.dev/core/auth/memoryauth"
)
func main() {
var driver auth.UserDriver = memoryauth.New()
_, err := driver.Find(context.Background(), "1")
fmt.Println(errors.Is(err, auth.ErrUserNotFound))
}
Output: true
type UserDriverBuilder ¶
type UserDriverBuilder[U any] struct { // contains filtered or unexported fields }
UserDriverBuilder configures NewUserDriver before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft. A nil function leaves the corresponding setting off.
Example:
driver, err := auth.NewUserDriver(loadUser, userID, func(driver *auth.UserDriverBuilder[User]) {
driver.Version(func(user User) string { return user.PasswordVersion })
})
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
func main() {
driver, _ := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Version(func(user exampleUser) string { return "v1" }).
Claims(func(user exampleUser) map[string]any { return map[string]any{"id": user.ID} }).
Disabled(func(user exampleUser) bool { return false })
},
)
record, _ := driver.Find(context.Background(), "5")
fmt.Println(record.Version, record.Claims["id"])
}
Output: v1 5
func (*UserDriverBuilder[U]) Claims ¶
func (builder *UserDriverBuilder[U]) Claims(claims func(U) map[string]any) *UserDriverBuilder[U]
Claims sets the function that derives UserRecord.Claims from a user. It replaces the previous value on the construction draft.
Example:
driver.Claims(func(user User) map[string]any { return map[string]any{"role": user.Role} })
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
record, _ := exampleDriver().Find(context.Background(), "1")
fmt.Println(record.Claims)
}
Output: map[role:admin]
func (*UserDriverBuilder[U]) Disabled ¶
func (builder *UserDriverBuilder[U]) Disabled(disabled func(U) bool) *UserDriverBuilder[U]
Disabled sets the function that reports a user that exists but may not act; TypedUserDriver.Find then returns ErrUserDisabled. It replaces the previous value on the construction draft.
Example:
driver.Disabled(func(user User) bool { return user.SuspendedAt != nil })
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
_, err := exampleDriver().Find(context.Background(), "2")
fmt.Println(err)
}
Output: auth: user disabled
func (*UserDriverBuilder[U]) Version ¶
func (builder *UserDriverBuilder[U]) Version(version func(U) string) *UserDriverBuilder[U]
Version sets the function that derives UserRecord.Version from a user. It replaces the previous value on the construction draft.
Example:
driver.Version(func(user User) string { return user.PasswordVersion })
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
func main() {
driver, _ := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Version(func(user exampleUser) string { return fmt.Sprint("v", user.ID) })
},
)
record, _ := driver.Find(context.Background(), "3")
fmt.Println(record.Version)
}
Output: v3
type UserDriverBuilderFunc ¶
type UserDriverBuilderFunc[U any] = func(*UserDriverBuilder[U])
UserDriverBuilderFunc configures a UserDriverBuilder.
Example:
var policy auth.UserDriverBuilderFunc[User] = func(driver *auth.UserDriverBuilder[User]) {
driver.Version(func(user User) string { return user.PasswordVersion })
}
driver, err := auth.NewUserDriver(loadUser, userID, policy)
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
func main() {
policy := auth.UserDriverBuilderFunc[exampleUser](func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Version(func(user exampleUser) string { return "v1" })
})
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
func(user exampleUser) int64 { return user.ID },
policy,
)
fmt.Println(driver != nil, err)
}
Output: true <nil>
type UserForgottenEvent ¶
type UserForgottenEvent struct {
// Subject is the subject passed to [UserProvider.Forget].
Subject string
}
UserForgottenEvent reports that every forget hook of a user completed. It carries only the subject, never personal data.
Example:
unsubscribe, err := events.Listen(auth.UserForgotten, func(ctx context.Context, forgotten auth.UserForgottenEvent) error {
logger.InfoContext(ctx, "user forgotten", "subject", forgotten.Subject)
return nil
})
Example ¶
package main
import (
"fmt"
"arkoren.dev/core/auth"
)
func main() {
forgotten := auth.UserForgottenEvent{Subject: "42"}
fmt.Println(auth.UserForgotten.Name(), forgotten.Subject)
}
Output: auth.user.forgotten 42
type UserProvider ¶
type UserProvider struct {
// contains filtered or unexported fields
}
UserProvider looks users up through a UserDriver and coordinates cleanup when a user is forgotten. It is safe for concurrent use.
Example:
users, err := auth.NewUserProvider(driver)
if err != nil {
return err
}
record, err := users.Find(ctx, "42")
func NewUserProvider ¶
func NewUserProvider(driver UserDriver, configure ...UserProviderBuilderFunc) (*UserProvider, error)
NewUserProvider returns a provider over driver. It returns an error when driver is nil. Construction callbacks configure UserProviderBuilder.
Example:
users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
users.Events(app.Events())
})
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
"arkoren.dev/core/event"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
users, err := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
users.Events(event.New())
})
if err != nil {
panic(err)
}
record, err := users.Find(context.Background(), "1")
fmt.Println(record.Subject, record.Claims["role"], err)
}
Output: 1 admin <nil>
func (*UserProvider) Find ¶
func (provider *UserProvider) Find(ctx context.Context, subject string) (UserRecord, error)
Find returns the record of subject from the driver. Errors are the driver's: see UserDriver for ErrInvalidSubject, ErrUserNotFound and ErrUserDisabled.
Example:
record, err := users.Find(ctx, subject)
if errors.Is(err, auth.ErrUserNotFound) {
return nil // The user was deleted.
}
Example ¶
package main
import (
"context"
"errors"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
users, _ := auth.NewUserProvider(exampleDriver())
_, err := users.Find(context.Background(), "2")
fmt.Println(errors.Is(err, auth.ErrUserDisabled))
_, err = users.Find(context.Background(), "3")
fmt.Println(errors.Is(err, auth.ErrUserNotFound))
}
Output: true true
func (*UserProvider) Forget ¶
func (provider *UserProvider) Forget(ctx context.Context, subject string) error
Forget removes the data of a user by running every hook registered with UserProvider.OnForget synchronously in ctx, in registration order, so the hooks join a transaction carried by ctx. The first hook error stops the run and is returned unchanged; hook panics propagate. It returns an error wrapping ErrInvalidSubject without running hooks for an invalid subject. After every hook succeeded it emits UserForgotten on the configured bus, and never after a failure. Forget does not look the user up.
Example:
err := db.WithTransaction(ctx, func(ctx context.Context) error {
if err := removeAccount(ctx, id); err != nil {
return err
}
return users.Forget(ctx, subject)
})
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
"arkoren.dev/core/event"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
events := event.New()
users, _ := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
users.Events(events)
})
_, _ = events.Listen(auth.UserForgotten, func(_ context.Context, forgotten auth.UserForgottenEvent) error {
fmt.Println("forgotten:", forgotten.Subject)
return nil
})
fmt.Println(users.Forget(context.Background(), "1"))
}
Output: forgotten: 1 <nil>
func (*UserProvider) OnForget ¶
func (provider *UserProvider) OnForget(hook func(ctx context.Context, subject string) error)
OnForget registers hook to delete the data a package keeps about a user. Hooks run in registration order by UserProvider.Forget. Deletes should be idempotent, so there are no names and no duplicate check. It is safe to call concurrently with Forget; a Forget already running uses the hooks registered before it started. It panics when hook is nil.
Example:
users.OnForget(func(ctx context.Context, subject string) error {
return subscriptions.DeleteBySubject(ctx, subject)
})
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
users, _ := auth.NewUserProvider(exampleDriver())
users.OnForget(func(_ context.Context, subject string) error {
fmt.Println("delete subscriptions of", subject)
return nil
})
users.OnForget(func(_ context.Context, subject string) error {
fmt.Println("delete sessions of", subject)
return nil
})
_ = users.Forget(context.Background(), "1")
}
Output: delete subscriptions of 1 delete sessions of 1
type UserProviderBuilder ¶
type UserProviderBuilder struct {
// contains filtered or unexported fields
}
UserProviderBuilder configures NewUserProvider before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft, and retaining it cannot change a published provider.
Example:
users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
users.Events(app.Events())
})
func (*UserProviderBuilder) Events ¶
func (builder *UserProviderBuilder) Events(events *event.Bus) *UserProviderBuilder
Events sets the bus that receives UserForgotten. Nil, the default, emits nothing. The bus is a shared service, not copied.
This setting replaces the previous value on the construction draft.
Example:
users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
users.Events(event.New())
})
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
"arkoren.dev/core/event"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
events := event.New()
users, _ := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
users.Events(events)
})
_, _ = events.Listen(auth.UserForgotten, func(context.Context, auth.UserForgottenEvent) error {
fmt.Println("event received")
return nil
})
_ = users.Forget(context.Background(), "1")
}
Output: event received
type UserProviderBuilderFunc ¶
type UserProviderBuilderFunc = func(*UserProviderBuilder)
UserProviderBuilderFunc configures a UserProviderBuilder.
Example:
var policy auth.UserProviderBuilderFunc = func(users *auth.UserProviderBuilder) {
users.Events(events)
}
users, err := auth.NewUserProvider(driver, policy)
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
"arkoren.dev/core/event"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
policy := auth.UserProviderBuilderFunc(func(users *auth.UserProviderBuilder) {
users.Events(event.New())
})
users, err := auth.NewUserProvider(exampleDriver(), policy)
fmt.Println(users != nil, err)
}
Output: true <nil>
type UserRecord ¶
type UserRecord struct {
// Subject is the user's subject as passed to Find.
Subject string
// Version is an opaque string that changes whenever the user changes in a
// way that should invalidate what was derived from it, such as a password
// version. Empty means the driver has no version.
Version string
// Claims are application-defined attributes of the user. Treat the map as
// read only: drivers may share it.
Claims map[string]any
// Value is the driver's own user value, such as the application's user
// struct. Its type is whatever the driver documents; nil if none.
Value any
}
UserRecord is what a UserDriver knows about one user.
Example:
record, err := users.Find(ctx, "42")
if err != nil {
return err
}
fmt.Println(record.Subject, record.Version, record.Claims["role"])
Example ¶
package main
import (
"context"
"fmt"
"arkoren.dev/core/auth"
)
// exampleUser is the application user of the examples.
type exampleUser struct {
ID int64
Role string
Suspended bool
}
// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}
driver, err := auth.NewUserDriver(
func(_ context.Context, id int64) (exampleUser, error) {
if user, ok := users[id]; ok {
return user, nil
}
return exampleUser{}, auth.ErrUserNotFound
},
func(user exampleUser) int64 { return user.ID },
func(driver *auth.UserDriverBuilder[exampleUser]) {
driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
driver.Disabled(func(user exampleUser) bool { return user.Suspended })
},
)
if err != nil {
panic(err)
}
return driver
}
func main() {
record, _ := exampleDriver().Find(context.Background(), "1")
fmt.Println(record.Subject, record.Claims["role"], record.Value.(exampleUser).ID)
}
Output: 1 admin 1
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package authtest provides conformance suites for auth.UserDriver and auth.Authenticator implementations, modeled on testing/fstest.
|
Package authtest provides conformance suites for auth.UserDriver and auth.Authenticator implementations, modeled on testing/fstest. |
|
Package gate authorizes the authenticated user with plain Go rules.
|
Package gate authorizes the authenticated user with plain Go rules. |
|
Package memoryauth provides an in-memory auth.UserDriver for tests, local development and single-process applications.
|
Package memoryauth provides an in-memory auth.UserDriver for tests, local development and single-process applications. |