Documentation
¶
Overview ¶
Package middleware adapts authentication.Authenticator to transports. It depends only on the standard library and the authentication contracts so that it can be imported without pulling in protocol implementations.
Index ¶
Examples ¶
Constants ¶
const ( // SourceAttribute names the transport location the credential came from. SourceAttribute = "source" // SourceAuthorization marks credentials from an Authorization value. SourceAuthorization = "authorization" // SourceCookie marks credentials from a cookie. SourceCookie = "cookie" )
Credential attribute names and values set by this package.
const MaxAuthorizationBytes = 16 << 10
MaxAuthorizationBytes bounds Authorization values accepted by CredentialFromAuthorizationHeader.
Variables ¶
This section is empty.
Functions ¶
func CredentialFromAuthorizationHeader ¶
func CredentialFromAuthorizationHeader(value string) (authentication.Credential, error)
CredentialFromAuthorizationHeader parses an RFC 6750 "Bearer" Authorization value, as used by HTTP headers and gRPC "authorization" metadata. Tokens in JWS compact form are returned with Kind authentication.CredentialKindJWT; all other tokens with authentication.CredentialKindBearer. The scheme is case-insensitive and the token must be an RFC 6750 b64token.
It returns authentication.ErrUnauthenticated for an empty value, authentication.ErrUnsupportedCredential for another scheme, and authentication.ErrInvalidCredential for a malformed bearer value. Errors never contain the value.
func HTTP ¶
func HTTP(next http.Handler, auth authentication.Authenticator, options ...Option) http.Handler
HTTP returns a handler that authenticates requests with auth and stores the principal with authentication.ContextWithPrincipal before calling next.
Credentials come from a single "Authorization: Bearer" header (see CredentialFromAuthorizationHeader) or, when configured, a single cookie. Missing credentials and other Authorization schemes yield 401 (a scheme other than Bearer is rejected even WithAnonymous), malformed or ambiguous credentials 400, and rejected credentials 401, each with an RFC 6750 WWW-Authenticate challenge and a generic body that never includes credential material or authenticator errors.
HTTP panics when next or auth is nil or an option is invalid.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/justusschock/auth/authentication"
"github.com/justusschock/auth/authentication/middleware"
)
// staticAuthenticator accepts one fixed bearer token.
type staticAuthenticator struct{}
func (staticAuthenticator) Authenticate(_ context.Context, credential authentication.Credential) (authentication.Principal, error) {
if string(credential.Token) != "let-me-in" {
return authentication.Principal{}, authentication.ErrUnauthenticated
}
return authentication.Principal{ID: "issuer|alice", Subject: "alice"}, nil
}
func main() {
app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
principal, _ := authentication.PrincipalFromContext(r.Context())
_, _ = fmt.Fprintf(w, "hello %s", principal.Subject)
})
handler := middleware.HTTP(app, authentication.Chain(staticAuthenticator{}), middleware.WithRealm("example"))
for _, header := range []string{"Bearer let-me-in", "Bearer wrong"} {
request := httptest.NewRequest(http.MethodGet, "/", nil)
request.Header.Set("Authorization", header)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code == http.StatusOK {
fmt.Println(recorder.Code, recorder.Body.String())
continue
}
fmt.Println(recorder.Code, recorder.Header().Get("WWW-Authenticate"))
}
}
Output: 200 hello alice 401 Bearer realm="example", error="invalid_token"
Types ¶
type Option ¶
type Option func(*config)
Option configures HTTP.
func WithAnonymous ¶
func WithAnonymous() Option
WithAnonymous passes requests that carry no credential to the next handler without a principal. Requests that carry an invalid credential are still rejected.
func WithCookie ¶
WithCookie also reads credentials of the given kind from the named cookie when no Authorization header is present. Cookie authentication is vulnerable to cross-site request forgery; callers must add CSRF protection (for example SameSite cookies plus origin checks) for state-changing routes.
func WithMaxTokenBytes ¶
WithMaxTokenBytes bounds accepted token sizes. The default is 8 KiB.