### Install WebAuthn Library Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/QUICK_START.md Install the WebAuthn library using the go get command. ```bash go get github.com/go-webauthn/webauthn ``` -------------------------------- ### Implement webauthn.User Interface Example Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/user-interface.md This example shows a concrete implementation of the `webauthn.User` interface. It includes fields for user identification and credentials, along with methods to satisfy the interface contract. ```go package main import ( "github.com/go-webauthn/webauthn/webauthn" ) // MyUser implements the webauthn.User interface type MyUser struct { ID int64 Username string DisplayName string WebAuthnID []byte // Stable, random user handle Credentials []webauthn.Credential } // WebAuthnID returns the user handle func (u *MyUser) WebAuthnID() []byte { return u.WebAuthnID } // WebAuthnName returns the username func (u *MyUser) WebAuthnName() string { return u.Username } // WebAuthnDisplayName returns the display name func (u *MyUser) WebAuthnDisplayName() string { return u.DisplayName } // WebAuthnCredentials returns the user's credentials func (u *MyUser) WebAuthnCredentials() []webauthn.Credential { return u.Credentials } ``` -------------------------------- ### FinishLogin Example Usage Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md Example of how to use the FinishLogin function. It demonstrates validating the assertion response and handling potential errors, including unknown credentials. It also shows how to update the user's sign counter and backup state after a successful login. ```go credential, err := wa.FinishLogin(user, session, httpRequest) if err != nil { if errors.Is(err, protocol.ErrorUnknownCredential{}.Err) { return fmt.Errorf("credential not registered") } return err } // Update sign counter and backup state user.Credentials[findCredentialIndex(user, credential.ID)].Authenticator.UpdateCounter(credential.Authenticator.SignCount) db.Save(user) ``` -------------------------------- ### Example: Using the Memory Metadata Provider Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/metadata.md Demonstrates how to fetch metadata, create an in-memory provider, and configure it for use. Handles potential errors during provider creation. ```go import ( "github.com/go-webauthn/webauthn/metadata" "github.com/go-webauthn/webauthn/metadata/providers/memory" ) // Fetch and use in memory md, _ := metadata.Fetch() provider, err := memory.New(md) if err != nil { log.Fatal(err) } config.MDS = provider ``` -------------------------------- ### FinishPasskeyLogin Example Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md Example usage of FinishPasskeyLogin to authenticate a user with a passkey. It demonstrates how to provide a user handler to query the user by their handle and process the authentication result. ```go user, credential, err := wa.FinishPasskeyLogin( func(rawID, userHandle []byte) (webauthn.User, error) { // Query user by user handle return db.FindUserByWebAuthnID(userHandle) }, session, httpRequest, ) if err != nil { return err } // User is now authenticated ``` -------------------------------- ### Finish Registration and Store Credential Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md This example demonstrates how to finish the WebAuthn registration process and store the verified credential in a database. It handles potential errors during verification. ```go credential, err := wa.FinishRegistration(user, session, httpRequest) if err != nil { return err } // Store credential in database userRecord.Credentials = append(userRecord.Credentials, *credential) db.Save(userRecord) ``` -------------------------------- ### Full Session Lifecycle Example Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/session-data.md Demonstrates the complete lifecycle of a WebAuthn registration session, from initiation to completion and credential storage. Ensure session data is securely stored and cleared after use. ```go // 1. Begin registration user := &MyUser{ID: []byte("user123")} creation, session, err := wa.BeginRegistration(user) if err != nil { return err } // 2. Store session securely sessionJSON, _ := json.Marshal(session) w.Header().Set("Set-Cookie", fmt.Sprintf( "webauthn_session=%s; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=600", base64.StdEncoding.EncodeToString(sessionJSON), )) // 3. Send creation to client w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(creation) // --- Later, client sends response --- // 4. Retrieve stored session from cookie cookie, _ := r.Cookie("webauthn_session") sessionJSON, _ := base64.StdEncoding.DecodeString(cookie.Value) var session SessionData json.Unmarshal(sessionJSON, &session) // 5. Verify credential credential, err := wa.FinishRegistration(user, session, r) if err != nil { return err } // 6. Clear session (important!) w.Header().Set("Set-Cookie", "webauthn_session=; Path=/; Max-Age=0") // 7. Store credential user.Credentials = append(user.Credentials, credential) db.Save(user) ``` -------------------------------- ### Minimal WebAuthn Configuration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/INDEX.md Use this minimal configuration for basic WebAuthn setup. Ensure RPID and RPOrigins are correctly set for your domain. ```go &webauthn.Config{ RPID: "example.com", RPOrigins: []string{"https://example.com"}, RPDisplayName: "My App", } ``` -------------------------------- ### Configuring WebAuthn Timeouts Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/config.md Example demonstrating how to set specific timeout durations and enforcement policies for login and registration ceremonies using the `TimeoutsConfig` structure. ```go config.Timeouts.Login.Timeout = 2 * time.Minute config.Timeouts.Login.TimeoutUVD = 60 * time.Second config.Timeouts.Login.Enforce = true config.Timeouts.Registration.Timeout = 2 * time.Minute config.Timeouts.Registration.Enforce = true ``` -------------------------------- ### Typical Production WebAuthn Configuration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/configuration.md This comprehensive Go configuration example covers typical production settings for the webauthn library. It includes domain, cross-origin, attestation, authenticator selection, timeouts, and optional metadata service and filtering configurations. ```go config := &webauthn.Config{ // Domain configuration RPID: "example.com", RPDisplayName: "Example App", RPOrigins: []string{ "https://example.com", "https://www.example.com", "https://app.example.com", }, // Cross-origin configuration (if needed) RPTopOrigins: []string{ "https://example.com", }, RPTopOriginVerificationMode: protocol.TopOriginExplicitVerificationMode, RPAllowCrossOrigin: false, // Attestation settings AttestationPreference: protocol.ConveyancePreferenceNone, // Authenticator selection defaults AuthenticatorSelection: protocol.AuthenticatorSelection{ UserVerification: protocol.VerificationPreferred, }, // Timeout configuration Timeouts: webauthn.TimeoutsConfig{ Login: webauthn.TimeoutConfig{ Enforce: true, Timeout: 60 * time.Second, TimeoutUVD: 30 * time.Second, }, Registration: webauthn.TimeoutConfig{ Enforce: true, Timeout: 60 * time.Second, TimeoutUVD: 30 * time.Second, }, }, // Metadata Service (optional) MDS: mdsProvider, // Filtering (optional) Filtering: &webauthn.FilteringConfig{ // Customize authenticator restrictions }, } wa, err := webauthn.New(config) ``` -------------------------------- ### Implement ConfigProvider Interface Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/configuration.md Implement the ConfigProvider interface to fetch configuration dynamically from external sources. This example shows how to query RPID and Origins from a database. ```go type DynamicConfig struct { db *sql.DB } func (c *DynamicConfig) GetRPID() string { // Query from database return c.db.QueryRow("SELECT value FROM config WHERE key = 'rpid'").String() } func (c *DynamicConfig) GetOrigins() []string { // Query from database // ... } // Use with ceremony methods that accept protocol.ConfigProvider ``` -------------------------------- ### Handle Login Assertion and Session Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md Example of initiating a login, handling potential errors, and preparing the session and assertion data for client transmission. Persist the session server-side. ```go assertion, session, err := wa.BeginLogin(user) if err != nil { return err } // Store session and send assertion to client sessionJSON, _ := json.Marshal(session) assertionJSON, _ := json.Marshal(assertion) // Persist session... w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(assertionJSON) ``` -------------------------------- ### Begin User Login Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/QUICK_START.md Start the WebAuthn login process by calling BeginLogin. This generates assertion options for the client and stores session data. Ensure the session is stored securely. ```go user, _ := db.GetUser("alice") assertion, session, err := wa.BeginLogin(user) if err != nil { return err } // Store session sessionJSON, _ := json.Marshal(session) http.SetCookie(w, &http.Cookie{ Name: "webauthn_session", Value: base64.StdEncoding.EncodeToString(sessionJSON), HttpOnly: true, Secure: true, }) // Send assertion options to client w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(assertion) ``` -------------------------------- ### RPOrigins Configuration Example Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/configuration.md Defines a list of allowed origins for WebAuthn authentication. Ensure origins include the protocol and domain, and match the client's request origin. Use specific ports if necessary. ```go RPOrigins: []string{ "https://example.com", "https://www.example.com", "https://app.example.com", "https://example.com:3000", // Specific port } ``` -------------------------------- ### File Manifest Overview Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/README.md This snippet outlines the directory structure and key files within the go-webauthn library. It helps users navigate the project and locate specific documentation or examples. ```text output/ ├── README.md (this file) ├── QUICK_START.md (minimal working example) ├── configuration.md (config options & environment setup) ├── types.md (type definitions reference) ├── errors.md (error catalog & handling) ├── api-reference/ │ ├── webauthn.md (core ceremony API) │ ├── credential.md (credential types & methods) │ ├── session-data.md (SessionData type & storage) │ ├── config.md (configuration types) │ ├── user-interface.md (User interface documentation) │ ├── registration-options.md (registration functional options) │ ├── login-options.md (login functional options) │ ├── protocol-parsing.md (low-level parsing functions) │ └── metadata.md (metadata service integration) ``` -------------------------------- ### Example PostgreSQL Storage Schema for WebAuthn Credentials Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/credential.md An example SQL schema for a PostgreSQL database table designed to store WebAuthn credential information. It includes fields for credential ID, public key, attestation details, and user-related information, with considerations for encryption and lookup. ```sql CREATE TABLE webauthn_credentials ( id UUID PRIMARY KEY, rpid VARCHAR(512) NOT NULL, user_id UUID NOT NULL, kid BYTEA NOT NULL, -- Credential.ID public_key BYTEA NOT NULL, -- Credential.PublicKey (encrypted) attestation_type VARCHAR(32), attestation_format VARCHAR(32), attestation BYTEA, -- Credential.Attestation (encrypted) sign_count BIGINT, clone_warning BOOLEAN, backup_eligible BOOLEAN, backup_state BOOLEAN ); ``` -------------------------------- ### Configure WebAuthn for Local Development Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/QUICK_START.md This example shows how to initialize the WebAuthn library for local development. It sets the Relying Party ID to 'localhost' and specifies the origin for the development server. Note that WebAuthn requires HTTPS except for localhost testing. ```go config := &webauthn.Config{ RPID: "localhost", RPOrigins: []string{"http://localhost:3000"}, RPDisplayName: "Local Dev", } wa, _ := webauthn.New(config) ``` -------------------------------- ### Example Usage of SelectAuthenticator Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/credential.md Demonstrates how to use SelectAuthenticator to create an AuthenticatorSelection object for platform authenticators with preferred user verification. This selection can then be used to begin a WebAuthn registration process. ```go selection := webauthn.SelectAuthenticator("platform", nil, "preferred") // Creates selection requiring platform authenticator with preferred user verification creation, session, _ := wa.BeginRegistration(user, webauthn.WithAuthenticatorSelection(selection)) ``` -------------------------------- ### Initialize Cached Metadata Provider Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/metadata.md Example of initializing the cached metadata provider with a custom directory path and refresh interval. This snippet demonstrates how to use the option functions with `cached.New`. ```go import "github.com/go-webauthn/webauthn/metadata/providers/cached" provider, err := cached.New( cached.WithDirectoryPath("/var/cache/webauthn-mds"), cached.WithRefreshInterval(24*time.Hour), ) if err != nil { log.Fatal(err) } config.MDS = provider ``` -------------------------------- ### Get WebAuthn Configuration from Environment Variables Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/configuration.md This Go function demonstrates how to read WebAuthn configuration parameters like RPID and origins from environment variables, providing default values if they are not set. It's useful for dynamic configuration in different deployment environments. ```go import "os" import "strings" func getConfig() (*webauthn.Config, error) { rpid := os.Getenv("WEBAUTHN_RPID") if rpid == "" { rpid = "example.com" } origins := strings.Split(os.Getenv("WEBAUTHN_ORIGINS"), ",") if len(origins) == 0 || origins[0] == "" { origins = []string{"https://example.com"} } return &webauthn.Config{ RPID: rpid, RPDisplayName: os.Getenv("WEBAUTHN_RP_NAME"), RPOrigins: origins, }, nil } ``` -------------------------------- ### Get Recommended Level 3 Credential Parameters Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/registration-options.md Obtain recommended WebAuthn Level 3 credential parameters, including ES256 and RS256. This set offers good compatibility across a wider range of authenticators. ```go func CredentialParametersRecommendedL3() []protocol.CredentialParameter ``` -------------------------------- ### Get Default Credential Parameters Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/registration-options.md Retrieves the default credential parameters, which are recommended for modern browsers supporting ES256. This is the simplest way to get a compatible set of parameters. ```go func CredentialParametersDefault() []protocol.CredentialParameter ``` -------------------------------- ### Begin User Registration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md Generates new registration data for the client and authenticator. Returns credential creation options and session data that must be securely stored. Use this to initiate the registration flow. ```Go creation, session, err := wa.BeginRegistration(user) if err != nil { return err } // Store session securely (e.g., in session store with opaque cookie) sessionJSON, _ := json.Marshal(session) // Persist sessionJSON... // Send creation to client as JSON creationJSON, _ := json.Marshal(creation) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(creationJSON) ``` -------------------------------- ### Check for ErrorUnknownCredential Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/types.md Example of how to check if an error is of type `ErrorUnknownCredential` using `errors.Is`. This is useful for handling cases where a credential is not found. ```go if errors.Is(err, &protocol.ErrorUnknownCredential{}) { // Credential not found; could signal removal to authenticator } ``` -------------------------------- ### Get Protocol Value from CredentialFlags Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/credential.md Retrieve the raw protocol value of the CredentialFlags. This is recommended for storage to ensure future compatibility. ```go func (f CredentialFlags) ProtocolValue() protocol.AuthenticatorFlags ``` -------------------------------- ### Begin User Registration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/MANIFEST.txt Initiate the user registration process by calling BeginRegistration. This generates a creation object and session data that should be stored and sent to the client. ```go creation, session, _ := wa.BeginRegistration(user) // Store session, send creation to client ``` -------------------------------- ### Initialize WebAuthn Instance Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md Creates a new WebAuthn instance using the provided configuration. The configuration is validated before the instance is returned. Use this to set up your relying party details. ```Go config := &webauthn.Config{ RPID: "example.com", RPOrigins: []string{"https://example.com"}, RPDisplayName: "My App", } wa, err := webauthn.New(config) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Handling ErrChallengeMismatch Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/errors.md Example of detecting and handling ErrChallengeMismatch during registration. This indicates a potential security risk (replay attack or session corruption) and should be logged. ```go credential, err := wa.FinishRegistration(user, session, request) if err == protocol.ErrChallengeMismatch { // Security risk: reject and log log.Printf("Challenge mismatch detected") } ``` -------------------------------- ### Runtime Configuration Changes Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/configuration.md Create multiple configuration instances to manage different settings, such as for a main domain and a testing subdomain. ```go // Main RP configuration mainConfig := &webauthn.Config{ RPID: "example.com", RPOrigins: []string{"https://example.com"}, } wa := webauthn.New(mainConfig) // Separate configuration for testing subdomain testConfig := &webauthn.Config{ RPID: "test.example.com", RPOrigins: []string{"https://test.example.com"}, } waTest := webauthn.New(testConfig) ``` -------------------------------- ### Handling ErrBadRequest Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/errors.md Example of checking for ErrBadRequest after a registration attempt. This error can indicate various parsing or validation issues, and DevInfo should be checked for specific details. ```go credential, err := wa.FinishRegistration(user, session, request) if err == protocol.ErrBadRequest { // Could be various parsing or validation issues // Check err.DevInfo for details } ``` -------------------------------- ### Begin MFA Login Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/MANIFEST.txt Initiates the multi-factor authentication login process. Stores the session and sends the assertion to the client. ```go assertion, session, _ := wa.BeginLogin(user) // Store session, send assertion to client ``` -------------------------------- ### Typical Application Flow for User Signup Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/README.md Illustrates the sequence of operations for user registration using WebAuthn, from generating creation options to verifying the attestation response. ```text User Signup: 1. Display signup form 2. User creates username, display name 3. Call BeginRegistration() → get creation options 4. Send options to client → authenticator creates credential 5. Client returns attestation response 6. Call FinishRegistration() → verify and store credential ``` -------------------------------- ### BeginDiscoverableMediatedLogin Function Signature Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md This is the function signature for BeginDiscoverableMediatedLogin. It is used to start a discoverable mediated login flow, allowing explicit control over credential mediation. ```go func (webauthn *WebAuthn) BeginDiscoverableMediatedLogin( mediation protocol.CredentialMediationRequirement, opts ...LoginOption ) ( assertion *protocol.CredentialAssertion, session *SessionData, err error ) ``` -------------------------------- ### Chaining WebAuthn Login Options Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/login-options.md Demonstrates how to chain multiple options when initiating a WebAuthn login. Options are applied in order, with later ones overriding earlier ones. ```go assertion, session, err := wa.BeginLogin(user, webauthn.WithUserVerification(protocol.VerificationRequired), webauthn.WithAssertionExtensions(protocol.AuthenticationExtensions{ "appid": "https://example.com", }), webauthn.WithAllowedCredentials(allowedDescriptors), ) ``` -------------------------------- ### Chain Multiple Registration Options Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/registration-options.md Demonstrates how to chain multiple registration options together to customize various aspects of the registration process. Options are applied in the order they are provided, with later options overriding earlier ones. ```go creation, session, err := wa.BeginRegistration(user, webauthn.WithExclusions(excludeList), webauthn.WithAuthenticatorSelection(protocol.AuthenticatorSelection{ UserVerification: protocol.VerificationRequired, }), webauthn.WithConveyancePreference(protocol.ConveyancePreferenceDirect), webauthn.WithAppIdExcludeExtension("https://example.com"), ) ``` -------------------------------- ### Begin Passwordless Login Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/MANIFEST.txt Initiates the passwordless login process. Stores the session and sends the assertion to the client. ```go assertion, session, _ := wa.BeginDiscoverableLogin() // Store session, send assertion to client ``` -------------------------------- ### Parse Credential Creation Response Bytes Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/protocol-parsing.md Parses a WebAuthn registration response from raw bytes. Use this when you have the response data as a byte slice, for example, after decoding from base64. ```go func ParseCredentialCreationResponseBytes(data []byte) ( *ParsedCredentialCreationData, error ) ``` ```go // From base64-encoded data encoded := "eyJpZCI6ImF1dGhlbnRpY2F0b3IuLi4ifQ==" data, _ := base64.StdEncoding.DecodeString(encoded) parsed, err := protocol.ParseCredentialCreationResponseBytes(data) ``` -------------------------------- ### Reverifying Credentials Against Updated Metadata Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/metadata.md After a credential has been registered, it can be reverified against potentially updated metadata, for example, during login or on a schedule. This helps catch changes in authenticator status, such as revocation. ```go // Reverify credential during login or on schedule err := credential.Verify(mdsProvider) if err != nil { log.Printf("Credential verification failed: %v", err) // Could indicate: // - Authenticator status changed (e.g., revoked) // - Attestation is no longer valid } ``` -------------------------------- ### Initialize WebAuthn Configuration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/config.md This snippet shows how to create and initialize a new WebAuthn configuration object. Ensure all required fields like RPID and RPOrigins are correctly set. ```go config := &webauthn.Config{ RPID: "example.com", RPDisplayName: "Example App", RPOrigins: []string{ "https://example.com", "https://www.example.com", }, RPTopOrigins: []string{ "https://app.example.com", }, RPTopOriginVerificationMode: protocol.TopOriginExplicitVerificationMode, AttestationPreference: protocol.ConveyancePreferenceNone, AuthenticatorSelection: protocol.AuthenticatorSelection{ AuthenticatorAttachment: protocol.Platform, UserVerification: protocol.VerificationPreferred, }, Timeouts: webauthn.TimeoutsConfig{ Login: webauthn.TimeoutConfig{ Enforce: true, Timeout: 60 * time.Second, TimeoutUVD: 30 * time.Second, }, Registration: webauthn.TimeoutConfig{ Enforce: true, Timeout: 60 * time.Second, TimeoutUVD: 30 * time.Second, }, }, } wa, err := webauthn.New(config) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Begin User Registration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/QUICK_START.md Initiate the WebAuthn registration process by calling BeginRegistration. This generates the necessary options for the client and stores session data. Ensure session data is stored securely. ```go user := &MyUser{ ID: "user123", Username: "alice", DisplayName: "Alice", WebAuthnID: generateRandomBytes(64), Credentials: []webauthn.Credential{}, } creation, session, err := wa.BeginRegistration(user) if err != nil { return err } // Store session securely (e.g., in HTTP session cookie) sessionJSON, _ := json.Marshal(session) http.SetCookie(w, &http.Cookie{ Name: "webauthn_session", Value: base64.StdEncoding.EncodeToString(sessionJSON), HttpOnly: true, Secure: true, }) // Send creation options to client w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(creation) ``` -------------------------------- ### Require User Verification for Login Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/QUICK_START.md Initiates a login flow that strictly requires user verification. This ensures that the user must actively verify their identity, for example, through biometrics or a PIN, before authentication is completed. ```go assertion, session, err := wa.BeginLogin(user, webauthn.WithUserVerification(protocol.VerificationRequired), ) ``` -------------------------------- ### New Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md Creates a new WebAuthn instance from the provided configuration. The configuration is validated before the instance is returned. ```APIDOC ## New ### Description Creates a new WebAuthn instance from the provided configuration. The configuration is validated before the instance is returned. ### Function Signature ```go func New(config *Config) (*WebAuthn, error) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | config | *Config | Yes | WebAuthn relying party configuration | ### Returns Table | Return | Type | Description | |--------|------|-------------| | webauthn | *WebAuthn | Initialized WebAuthn instance | | err | error | Configuration validation error, if any | ### Example ```go config := &webauthn.Config{ RPID: "example.com", RPOrigins: []string{"https://example.com"}, RPDisplayName: "My App", } wa, err := webauthn.New(config) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Fetch Production Metadata Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/metadata.md Fetches the current production metadata from the official FIDO Metadata Service. It creates a new HTTP client and retrieves the latest BLOB. Use this to get the latest metadata for validation. ```go import "github.com/go-webauthn/webauthn/metadata" // Fetch latest metadata md, err := metadata.Fetch() if err != nil { log.Fatal("Failed to fetch metadata:", err) } // Use with memory provider provider, _ := memory.New(md) ``` -------------------------------- ### Chaining Options Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/login-options.md Demonstrates how multiple options can be chained together when initiating a login flow. Later options override earlier ones. ```APIDOC ## Chaining Options Multiple options can be chained together: ```go assertion, session, err := wa.BeginLogin(user, webauthn.WithUserVerification(protocol.VerificationRequired), webauthn.WithAssertionExtensions(protocol.AuthenticationExtensions{ "appid": "https://example.com", }), webauthn.WithAllowedCredentials(allowedDescriptors), ) ``` Options are applied in order, so later options override earlier ones. ``` -------------------------------- ### Get Extended Level 3 Credential Parameters Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/registration-options.md Retrieves extended WebAuthn Level 3 credential parameters (ES256, RS256, EdDSA, etc.) for maximum authenticator compatibility. Use this when broad support is critical. ```go func CredentialParametersExtendedL3() []protocol.CredentialParameter ``` -------------------------------- ### Set Public Key Credential Hints Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/registration-options.md Use `WithPublicKeyCredentialHints` to provide hints to the user agent about preferred credential types and creation context, such as security keys or hybrid authenticators. ```go func WithPublicKeyCredentialHints(hints []protocol.PublicKeyCredentialHints) RegistrationOption ``` ```go hints := []protocol.PublicKeyCredentialHints{ protocol.HintSecurityKey, protocol.HintHybrid, } creation, session, _ := wa.BeginRegistration(user, webauthn.WithPublicKeyCredentialHints(hints)) ``` -------------------------------- ### Import Main API Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/README.md Import the main WebAuthn API package for core functionality. ```go // Main API import "github.com/go-webauthn/webauthn/webauthn" ``` -------------------------------- ### Chaining Options Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/registration-options.md Demonstrates how to chain multiple registration options together. ```APIDOC ## Chaining Options Multiple options can be chained together: ```go creation, session, err := wa.BeginRegistration(user, webauthn.WithExclusions(excludeList), webauthn.WithAuthenticatorSelection(protocol.AuthenticatorSelection{ UserVerification: protocol.VerificationRequired, }), webauthn.WithConveyancePreference(protocol.ConveyancePreferenceDirect), webauthn.WithAppIdExcludeExtension("https://example.com"), ) ``` Options are applied in order, so later options override earlier ones. ``` -------------------------------- ### Import Protocol Package Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/README.md Import the protocol package for handling WebAuthn protocol types and parsing. ```go // Protocol types and parsing import "github.com/go-webauthn/webauthn/protocol" ``` -------------------------------- ### Initialize WebAuthn Configuration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/MANIFEST.txt Initialize the WebAuthn configuration with Relying Party ID, origins, and display name. This is the first step before any WebAuthn operations. ```go config := &webauthn.Config{ RPID: "example.com", RPOrigins: []string{"https://example.com"}, RPDisplayName: "My App", } wa, _ := webauthn.New(config) ``` -------------------------------- ### Typical Application Flow for User Login (MFA) Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/README.md Outlines the steps for multi-factor authentication login using WebAuthn, involving generating assertion options and verifying the assertion response. ```text User Login (MFA): 1. User enters username 2. Call BeginLogin() → get assertion options 3. Send options to client → authenticator asserts credential 4. Client returns assertion response 5. Call FinishLogin() → verify and authenticate ``` -------------------------------- ### Test MDS with In-Memory Provider Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/metadata.md Set up an in-memory metadata provider for testing purposes. This involves creating a metadata struct with test entries and initializing the provider. ```go // Use memory provider with static test data testMetadata := &metadata.Metadata{ Parsed: metadata.Parsed{ Entries: []metadata.Entry{ // Add test authenticator entries }, }, } provider, _ := memory.New(testMetadata) config.MDS = provider ``` -------------------------------- ### Typical Application Flow for User Login (Passwordless) Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/README.md Describes the process for passwordless login using discoverable credentials with WebAuthn, including user lookup and authentication. ```text User Login (Passwordless): 1. No login field 2. Call BeginDiscoverableLogin() → get assertion options 3. Send options to client → authenticator asserts discoverable credential 4. Client returns assertion response + user handle 5. Call FinishPasskeyLogin() with user lookup handler → authenticate ``` -------------------------------- ### Initialize Cached Metadata Service Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/MANIFEST.txt Initializes a new cached metadata service with a specified directory path for storing metadata. ```go mds, _ := cached.New(cached.WithDirectoryPath("/var/cache/mds")) config.MDS = mds ``` -------------------------------- ### Set WebAuthn Extensions for Registration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/registration-options.md Use WithExtensions to configure optional features like HMAC secret or large blob storage for the registration ceremony. Pass a map of extension names to their configurations. ```go extensions := protocol.AuthenticationExtensions{ "appidExclude": "https://example.com", } creation, session, _ := wa.BeginRegistration(user, webauthn.WithExtensions(extensions)) ``` -------------------------------- ### Customize Credential Parameters for Registration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/QUICK_START.md Begins the user registration process, allowing customization of the allowed credential parameters. This snippet demonstrates how to specify different public key credential types and signature algorithms. ```go creation, session, err := wa.BeginRegistration(user, webauthn.WithCredentialParameters([]protocol.CredentialParameter{ {Type: protocol.PublicKeyCredentialType, Algorithm: webauthncose.AlgES256}, {Type: protocol.PublicKeyCredentialType, Algorithm: webauthncose.AlgRS256}, }), ) ``` -------------------------------- ### PublicKeyCredentialCreationOptions Structure Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/types.md Defines options for credential creation, sent from the Relying Party (RP) to the client and authenticator. Includes user and authenticator selection criteria. ```go type PublicKeyCredentialCreationOptions struct { RelyingParty protocol.RelyingPartyEntity User protocol.UserEntity Challenge protocol.URLEncodedBase64 Parameters []protocol.CredentialParameter Timeout int AuthenticatorSelection protocol.AuthenticatorSelection Attestation protocol.ConveyancePreference Excludeimports []protocol.CredentialDescriptor Extensions protocol.AuthenticationExtensions } ``` -------------------------------- ### Development Configuration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/configuration.md Use this configuration for local development and testing. It enables debug output and disables timeouts for easier debugging. ```go config := &webauthn.Config{ RPID: "localhost", RPDisplayName: "Local Dev", RPOrigins: []string{ "http://localhost:3000", "http://localhost:8080", "http://127.0.0.1:3000", }, Debug: true, // Enable debug output // Disable timeouts for easier testing Timeouts: webauthn.TimeoutsConfig{ Login: webauthn.TimeoutConfig{ Enforce: false, Timeout: 10 * time.Minute, }, Registration: webauthn.TimeoutConfig{ Enforce: false, Timeout: 10 * time.Minute, }, }, } ``` -------------------------------- ### WebAuthn User Registration Flow Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/user-interface.md Illustrates the steps for registering a new WebAuthn credential for a user. This involves beginning the registration process, storing session data, and finishing the registration after client interaction. ```go // User provides username and display name user := &MyUser{ ID: generateUserID(), Username: req.Username, DisplayName: req.DisplayName, WebAuthnID: generateWebAuthnID(), Credentials: []webauthn.Credential{}, } // Save user db.CreateUser(user) // Begin registration creation, session, err := wa.BeginRegistration(user) if err != nil { return err } // Store session, send creation to client... // Later, after client response: credential, err := wa.FinishRegistration(user, session, httpRequest) if err != nil { return err } // Add credential to user and save user.Credentials = append(user.Credentials, *credential) db.UpdateUser(user) ``` -------------------------------- ### Mock User Implementation for Unit Tests Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/QUICK_START.md This Go code defines a mock implementation of the User interface for use in unit tests. It includes fields for user ID, name, display name, and credentials, along with methods to satisfy the WebAuthn User interface. ```go // Mock User interface type mockUser struct { id []byte name string displayName string credentials []webauthn.Credential } func (u *mockUser) WebAuthnID() []byte { return u.id } func (u *mockUser) WebAuthnName() string { return u.name } func (u *mockUser) WebAuthnDisplayName() string { return u.displayName } func (u *mockUser) WebAuthnCredentials() []webauthn.Credential { return u.credentials } // Use in tests user := &mockUser{ id: []byte("test-user"), name: "test", displayName: "Test User", } ``` -------------------------------- ### WebAuthn Multi-Factor Login Flow Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/user-interface.md Shows how to implement multi-factor login using WebAuthn. This flow begins by identifying the user, initiating the login assertion, and then finishing the login process after client verification. ```go // Application knows user identity user, err := db.GetUserByUsername(username) if err != nil { return fmt.Errorf("user not found") } // Begin login with known user assertion, session, err := wa.BeginLogin(user) if err != nil { return err } // Store session, send assertion to client... // Later, after client response: credential, err := wa.FinishLogin(user, session, httpRequest) if err != nil { return err } // User authenticated; update credential counter idx := findCredentialIndex(user, credential.ID) user.Credentials[idx].Authenticator.UpdateCounter(credential.Authenticator.SignCount) db.UpdateUser(user) ``` -------------------------------- ### Metadata Validation Steps During Registration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/metadata.md During the FinishRegistration process, the library performs several steps to verify the attestation statement against metadata. If no metadata entry is found or validation fails, an error is returned. ```go // During FinishRegistration: // 1. Attestation statement is verified // 2. AAGUID from attestation is extracted // 3. Metadata entry for AAGUID is looked up // 4. Attestation is validated against metadata trust anchors // 5. If no entry or validation fails, error is returned ``` -------------------------------- ### Implement Discoverable User Handler for Passkey Login Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/login-options.md Implement the `DiscoverableUserHandler` to find a user based on credential ID and user handle during passkey login. This handler is crucial for verifying the user and their associated credentials. ```go handler := func(rawID, userHandle []byte) (webauthn.User, error) { // Look up user by userHandle (the WebAuthn user ID) user, err := db.FindUserByWebAuthnID(userHandle) if err != nil { return nil, fmt.Errorf("user not found: %w", err) } // Optionally verify credential exists for this user credentialFound := false for _, cred := range user.WebAuthnCredentials() { if bytes.Equal(cred.ID, rawID) { credentialFound = true break } } if !credentialFound { return nil, fmt.Errorf("credential not found for user") } return user, nil } user, credential, err := wa.FinishPasskeyLogin(handler, session, httpRequest) ``` -------------------------------- ### Configure Login and Registration Timeouts Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/configuration.md Set server-side enforced timeouts for login and registration operations. Use shorter timeouts for login as the user is already known. Consider device capabilities for longer timeouts. ```go config.Timeouts = webauthn.TimeoutsConfig{ Login: webauthn.TimeoutConfig{ Enforce: true, // Enforce server-side Timeout: 60 * time.Second, // With user verification TimeoutUVD: 30 * time.Second, // Without user verification }, Registration: webauthn.TimeoutConfig{ Enforce: true, Timeout: 60 * time.Second, TimeoutUVD: 30 * time.Second, }, } ``` -------------------------------- ### Define CredentialCreation Wrapper Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/types.md Wraps creation options with mediation information for WebAuthn credential creation. It includes the response options and the credential mediation requirement. ```go type CredentialCreation struct { Response protocol.PublicKeyCredentialCreationOptions Mediation protocol.CredentialMediationRequirement } ``` -------------------------------- ### BeginRegistration Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md Generates a new set of registration data to be sent to the client and authenticator. Returns credential creation options and session data that must be securely stored. ```APIDOC ## BeginRegistration ### Description Generates a new set of registration data to be sent to the client and authenticator. Returns credential creation options and session data that must be securely stored. ### Method Signature ```go func (webauthn *WebAuthn) BeginRegistration(user User, opts ...RegistrationOption) ( creation *protocol.CredentialCreation, session *SessionData, err error ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | user | User | Yes | User account implementing the User interface | | opts | ...RegistrationOption | No | Functional options to modify creation options | ### Returns Table | Return | Type | Description | |--------|------|-------------| | creation | *protocol.CredentialCreation | Credential creation options to send to client | | session | *SessionData | Session state to store server-side | | err | error | Error if registration cannot begin | ### Example ```go creation, session, err := wa.BeginRegistration(user) if err != nil { return err } // Store session securely (e.g., in session store with opaque cookie) sessionJSON, _ := json.Marshal(session) // Persist sessionJSON... // Send creation to client as JSON creationJSON, _ := json.Marshal(creation) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(creationJSON) ``` ``` -------------------------------- ### Import Metadata Services Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/README.md Import packages for metadata service providers, including memory and cached implementations. ```go // Metadata service providers import "github.com/go-webauthn/webauthn/metadata" import "github.com/go-webauthn/webauthn/metadata/providers/memory" import "github.com/go-webauthn/webauthn/metadata/providers/cached" ``` -------------------------------- ### Wrapping WebAuthn Errors Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/errors.md Demonstrates how to wrap and enhance errors using methods like WithDetails, WithInfo, and WithError to add context. ```go // Errors can be wrapped and enhanced using methods: // - WithDetails(string) *Error - Add user-facing message // - WithInfo(string) *Error - Add debug information // - WithError(error) *Error - Wrap underlying error ``` -------------------------------- ### Clone Detection and Counter Update Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/README.md Implement clone detection by checking the `CloneWarning` flag on the authenticator after login. If a clone is detected, appropriate actions like alerting the user should be taken. The authenticator's sign counter must be updated after each successful login. ```go // Check after every login credential, _ := wa.FinishLogin(user, session, request) if credential.Authenticator.CloneWarning { log.Printf("Clone detected for user %s", user.WebAuthnName()) // Alert user or require additional action } // Update counter credential.Authenticator.UpdateCounter(credential.Authenticator.SignCount) ``` -------------------------------- ### Create In-Memory Metadata Provider Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/metadata.md Creates an in-memory metadata provider by loading the entire metadata blob into memory. This is suitable for applications prioritizing memory efficiency over up-to-date attestation data. ```go import "github.com/go-webauthn/webauthn/metadata/providers/memory" func memory.New(metadata *metadata.Metadata) (Provider, error) ``` -------------------------------- ### WithPublicKeyCredentialHints Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/registration-options.md Sets hints about the preferred credential types and creation context for the user agent. This helps the browser or authenticator understand the user's intent, such as preferring a security key or a platform authenticator. ```APIDOC ## WithPublicKeyCredentialHints ### Description Sets hints about the preferred credential types and creation context for the user agent. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```go func WithPublicKeyCredentialHints(hints []protocol.PublicKeyCredentialHints) RegistrationOption ``` ### Parameters - **hints** ([]protocol.PublicKeyCredentialHints) - Required - Hints for the authenticator (e.g., security key, platform, hybrid) ### Request Example ```go hints := []protocol.PublicKeyCredentialHints{ protocol.HintSecurityKey, protocol.HintHybrid, } creation, session, _ := wa.BeginRegistration(user, webauthn.WithPublicKeyCredentialHints(hints)) ``` ``` -------------------------------- ### Configure Attestation Preference Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/configuration.md Set the attestation preference based on security requirements. Options range from no attestation to direct or enterprise attestation, with recommendations for metadata service validation. ```go // No attestation (default, privacy-friendly) config.AttestationPreference = protocol.ConveyancePreferenceNone // Best effort attestation (indirect) config.AttestationPreference = protocol.ConveyancePreferenceIndirect // Full attestation (requires MDS validation for security) config.AttestationPreference = protocol.ConveyancePreferenceDirect // Enterprise attestation (additional metadata) config.AttestationPreference = protocol.ConveyancePreferenceEnterprise ``` -------------------------------- ### WebAuthn Relying Party Configuration Structure Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/config.md Defines the structure for configuring WebAuthn operations. RPID and RPOrigins are mandatory. RPID should be the effective domain (e.g., 'example.com'), and RPOrigins must include all permitted fully qualified origins (e.g., 'https://example.com'). ```go type Config struct { RPID string RPDisplayName string RPOrigins []string RPTopOrigins []string RPTopOriginVerificationMode protocol.TopOriginVerificationMode RPAllowCrossOrigin bool AttestationPreference protocol.ConveyancePreference AuthenticatorSelection protocol.AuthenticatorSelection Debug bool EncodeUserIDAsString bool Timeouts TimeoutsConfig MDS metadata.Provider Filtering *FilteringConfig } ``` -------------------------------- ### Create New Credential Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/credential.md Constructs a new `Credential` object from validated client data and parsed creation data. Use this after a successful authenticator registration response. ```go func NewCredential(clientDataHash []byte, c *protocol.ParsedCredentialCreationData) ( credential *Credential, err error ) ``` ```go creation, session, err := wa.BeginRegistration(user) // ... send creation to client, receive response ... parsed, _ := protocol.ParseCredentialCreationResponseBytes(responseBytes) credential, err := webauthn.NewCredential(clientDataHash, parsed) if err != nil { return err } // Store credential user.Credentials = append(user.Credentials, *credential) ``` -------------------------------- ### Begin Multi-Factor Login Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/webauthn.md Creates the assertion data payload for a multi-factor authentication login ceremony. The user identity must be known before this call. Functional options can modify assertion options. ```go func (webauthn *WebAuthn) BeginLogin( user User, opts ...LoginOption ) ( assertion *protocol.CredentialAssertion, session *SessionData, err error ) ``` -------------------------------- ### Passwordless Login (Discoverable Credentials) Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/api-reference/login-options.md Initiates a WebAuthn login where the user's identity is not yet known, utilizing discoverable credentials (passkeys). ```go // User identity not known yet assertion, session, err := wa.BeginDiscoverableLogin( webauthn.WithUserVerification(protocol.VerificationPreferred), ) // Store session... // Send assertion to client... // Later, after client response: user, credential, err := wa.FinishPasskeyLogin( func(rawID, userHandle []byte) (webauthn.User, error) { return db.FindUserByWebAuthnID(userHandle) }, session, httpRequest, ) ``` -------------------------------- ### Enable Metadata Service with Caching Source: https://github.com/go-webauthn/webauthn/blob/master/_autodocs/QUICK_START.md Configures the WebAuthn client to use a metadata service provider that caches metadata locally. This improves performance by reducing external lookups and allows specifying a directory for cache storage and a refresh interval. ```go import "github.com/go-webauthn/webauthn/metadata/providers/cached" mds, _ := cached.New( cached.WithDirectoryPath("/var/cache/webauthn-mds"), cached.WithRefreshInterval(7*24*time.Hour), ) config := &webauthn.Config{ RPID: "example.com", RPOrigins: []string{"https://example.com"}, RPDisplayName: "My App", MDS: mds, } ```