Documentation
¶
Overview ¶
Package webauthn contains the API functionality of the library. After creating and configuring a webauthn object, users can call the object to create and validate web authentication credentials.
This documentation section highlights key functions within the library which are recommended and often have examples attached. Functions which are discouraged due to their lack of functionality are expressly not documented here, and you're on your own with these functions. Generally speaking, if the function is not documented here, it is either used by another function documented here, and it hides one of the arguments or return values, or it is lower level logic only intended for advanced use cases.
The New function is a key function in creating a new instance of a WebAuthn Relying Party which is required to perform most actions.
To start the credential creation ceremony, the WebAuthn.BeginMediatedRegistration or WebAuthn.BeginRegistration functions are used which returns *SessionData and a *protocol.CredentialCreation struct which can be easily serialized as JSON for the frontend library/logic. The *SessionData must be saved in a way which allows the implementer to restore it later. This *SessionData should be safely anchored to a user agent without allowing the user agent to modify the contents (i.e. opaque session cookie).
To finish the credential creation ceremony, the WebAuthn.FinishRegistration function can be used. This function requires a *http.Request and performs all the necessary and requested validations. If you have other requirements, you can use protocol.ParseCredentialCreationResponseBody or protocol.ParseCredentialCreationResponseBytes which require an io.Reader or byte array respectively, then use WebAuthn.CreateCredential to perform validations against the *protocol.ParsedCredentialCreationData and saved *SessionData and finalize the process. For complete customizability, just produce the *protocol.ParsedCredentialCreationData with a custom parser and provide it to WebAuthn.CreateCredential.
To start a Passkey login ceremony, the WebAuthn.BeginDiscoverableMediatedLogin or WebAuthn.BeginDiscoverableLogin functions are used which returns *SessionData and a *protocol.CredentialAssertion struct which can easily be serialized as JSON for the frontend library/logic. The *SessionData should be safely handled as previously described.
To finish a Passkey login ceremony, the WebAuthn.FinishPasskeyLogin function can be used. This function requires a *http.Request and performs all the necessary validations. If you have other requirements, you can use the protocol.ParseCredentialRequestResponseBody or protocol.ParseCredentialRequestResponseBytes which require an io.Reader or byte array respectively, then use WebAuthn.ValidatePasskeyLogin to perform validations against the *protocol.ParsedCredentialAssertionData and saved *SessionData and finalize the process. For complete customizabilty, just produce the protocol.ParsedCredentialAssertionData with a custom parser and provide it to WebAuthn.ValidatePasskeyLogin.
To start a Multi-Factor login ceremony, the WebAuthn.BeginMediatedLogin or WebAuthn.BeginLogin functions are used which returns SessionData and a *protocol.CredentialAssertion struct which can easily be serialized as JSON for the frontend library/logic. The *SessionData should be safely handled as previously described.
To finish a Multi-Factor login ceremony, the WebAuthn.FinishLogin function can be used. This function requires a *http.Request and performs all the necessary validations. If you have other requirements, you can use the protocol.ParseCredentialRequestResponseBody or protocol.ParseCredentialRequestResponseBytes which require an io.Reader or byte array respectively, then use WebAuthn.ValidateLogin to perform validations against the *protocol.ParsedCredentialAssertionData and saved *SessionData and finalize the process. For complete customizabilty, just produce the protocol.ParsedCredentialAssertionData with a custom parser and provide it to WebAuthn.ValidateLogin.
Example (MultiFactorRegisterAndLogin) ¶
Example_multiFactorRegisterAndLogin demonstrates handling Multi Factor registration and Logins. This uses the higher level APIs to perform all of the various requirements. The Crude and Abstract examples are purely domain logic and will often describe aspects that should be considered during their implementation if they are important; these aspects are not strictly concerns related to the library as there are too many logical implementations to count.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
)
// Example_multiFactorRegisterAndLogin demonstrates handling Multi Factor registration and Logins. This uses the higher level APIs to
// perform all of the various requirements. The Crude and Abstract examples are purely domain logic and will often
// describe aspects that should be considered during their implementation if they are important; these aspects
// are not strictly concerns related to the library as there are too many logical implementations to count.
func main() {
config := &webauthn.Config{
RPDisplayName: "Go WebAuthn",
RPID: "app.awesome-go-webauthn.com",
RPOrigins: []string{"https://app.awesome-go-webauthn.com"},
}
w, err := webauthn.New(config)
if err != nil {
// Crude example of error handling.
panic(err)
}
mux := http.NewServeMux()
// Register the handlers. The second component describes the action (i.e. register/login), the final component
// describes the step (i.e. start/finish).
mux.HandleFunc("/webauthn/register/start", handlerExampleMultiFactorCreateChallenge(w))
mux.HandleFunc("/webauthn/register/finish", handlerExampleMultiFactorValidateCreateChallengeResponse(w))
mux.HandleFunc("/webauthn/login/start", handlerExampleMultiFactorLoginChallenge(w))
mux.HandleFunc("/webauthn/login/finish", handlerExampleMultiFactorLoginChallengeResponse(w))
// Crude example that assumes the app is handled exclusively by a proxy which handles TLS termination. You will
// have to adjust this depending on the context to ensure TLS is used on port 443 or the relevant config options
// are adjusted.
server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
ReadHeaderTimeout: 2 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20,
}
if err = server.ListenAndServe(); err != nil {
panic(err)
}
}
var sessionExampleMultiFactor *webauthn.SessionData
func saveSessionExampleMultiFactor(s *webauthn.SessionData) {
sessionExampleMultiFactor = s
}
func loadSessionExampleMultiFactor() (*webauthn.SessionData, error) {
if sessionExampleMultiFactor == nil {
return nil, fmt.Errorf("no session found")
}
return sessionExampleMultiFactor, nil
}
func handlerExampleMultiFactorCreateChallenge(w *webauthn.WebAuthn) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Crude / Abstract example of retrieving the user this registration will belong to. The user must be logged in
// for this step unless you plan to register the user and the credential at the same time i.e. usernameless.
// The user should have a unique and stable value returned from WebAuthnID that can be used to retrieve the
// account details for the user.
user, err := LoadUser()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
var (
creation *protocol.CredentialCreation
s *webauthn.SessionData
)
opts := []webauthn.RegistrationOption{
webauthn.WithExclusions(webauthn.Credentials(user.WebAuthnCredentials()).CredentialDescriptors()),
webauthn.WithExtensions(map[string]any{"credProps": true}),
}
if creation, s, err = w.BeginMediatedRegistration(user, protocol.MediationDefault, opts...); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude example saving the session data securely to be loaded in the finish step of the register action. This
// should be stored in such a way that the user and user agent has no access to it. For example using an opaque
// session cookie.
saveSessionExampleMultiFactor(s)
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(http.StatusOK)
encoder := json.NewEncoder(rw)
if err = encoder.Encode(creation); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
}
func handlerExampleMultiFactorValidateCreateChallengeResponse(w *webauthn.WebAuthn) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Crude / Abstract example of retrieving the user performing the multi-factor authentication. The user must be
// logged in for this step.
user, err := LoadUser()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude example loading the session data securely from the start step for the register action. This should be
// loaded from a place the user and user agent has no access to it. For example using an opaque session cookie.
s, err := loadSessionExampleMultiFactor()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
credential, err := w.FinishRegistration(user, *s, r)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude / Abstract example of adding the credential to the list of credentials for the user. This is critical
// for performing future logins.
user.credentials = append(user.credentials, *credential)
// Crude / Abstract example of saving the updated user. This is critical for performing future logins.
if err = SaveUser(user); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(http.StatusOK)
}
}
func handlerExampleMultiFactorLoginChallenge(w *webauthn.WebAuthn) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Crude / Abstract example of retrieving the user for this multi-factor authentication. Because this is a
// multi-factor authentication the user MUST be logged in at this stage and the returned struct/interface must
// be deterministically matched to their account.
user, err := LoadUser()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
assertion, s, err := w.BeginMediatedLogin(user, protocol.MediationDefault)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude example saving the session data securely to be loaded in the finish step of the login action. This
// should be stored in such a way that the user and user agent has no access to it. For example using an opaque
// session cookie.
saveSessionExampleMultiFactor(s)
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(http.StatusOK)
encoder := json.NewEncoder(rw)
if err = encoder.Encode(assertion); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
}
func handlerExampleMultiFactorLoginChallengeResponse(w *webauthn.WebAuthn) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Crude / Abstract example of retrieving the user performing the multi-factor authentication. The user must be
// logged in for this step.
user, err := LoadUser()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude example loading the session data securely from the start step for the login action. This should be
// loaded from a place the user and user agent has no access to it. For example using an opaque session cookie.
s, err := loadSessionExampleMultiFactor()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
validatedCredential, err := w.FinishLogin(user, *s, r)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
var found bool
// Modify the matching credential in the user struct which is critical for proper future validations as the
// metadata for this credential has been updated. No type assertion is required here since the LoadUser function
// returns the concrete implementation, you may have to adjust this if you return the abstract implementation
// instead.
for i, credential := range user.credentials {
if bytes.Equal(validatedCredential.ID, credential.ID) {
user.credentials[i] = *validatedCredential
// Crude / Abstract example of saving the user with their updated credentials. This is critical for
// proper future validations.
if err = SaveUser(user); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
found = true
break
}
}
// Should error if we can't update the credentials for the user.
if !found {
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(http.StatusOK)
}
}
Output:
Example (NewRelyingParty) ¶
Example_newRelyingParty demonstrates initializing a relying party.
package main
import (
"github.com/go-webauthn/webauthn/webauthn"
)
func main() {
config := &webauthn.Config{
RPDisplayName: "Go WebAuthn",
RPID: "app.awesome-go-webauthn.com",
RPOrigins: []string{"https://app.awesome-go-webauthn.com"},
}
handler, err := webauthn.New(config)
if err != nil {
panic(err)
}
_ = handler
}
Output:
Example (PasskeysRegisterAndLogin) ¶
Example_passkeysRegisterAndLogin demonstrates handling Passkey registration and Logins. This uses the higher level APIs to perform all of the various requirements. The Crude and Abstract examples are purely domain logic and will often describe aspects that should be considered during their implementation if they are important; these aspects are not strictly concerns related to the library as there are too many logical implementations to count.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
)
// Example_passkeysRegisterAndLogin demonstrates handling Passkey registration and Logins. This uses the higher level APIs to
// perform all of the various requirements. The Crude and Abstract examples are purely domain logic and will often
// describe aspects that should be considered during their implementation if they are important; these aspects
// are not strictly concerns related to the library as there are too many logical implementations to count.
func main() {
config := &webauthn.Config{
RPDisplayName: "Go WebAuthn",
RPID: "app.awesome-go-webauthn.com",
RPOrigins: []string{"https://app.awesome-go-webauthn.com"},
}
w, err := webauthn.New(config)
if err != nil {
// Crude example of error handling.
panic(err)
}
mux := http.NewServeMux()
// Register the handlers. The second component describes the action (i.e. register/login), the final component
// describes the step (i.e. start/finish).
mux.HandleFunc("/webauthn/register/start", handlerExamplePasskeyCreateChallenge(w))
mux.HandleFunc("/webauthn/register/finish", handlerExamplePasskeyValidateCreateChallengeResponse(w))
mux.HandleFunc("/webauthn/login/start", handlerExamplePasskeyLoginChallenge(w))
mux.HandleFunc("/webauthn/login/finish", handlerExamplePasskeyLoginChallengeResponse(w))
// Crude example that assumes the app is handled exclusively by a proxy which handles TLS termination. You will
// have to adjust this depending on the context to ensure TLS is used on port 443 or the relevant config options
// are adjusted.
server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
ReadHeaderTimeout: 2 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20,
}
if err = server.ListenAndServe(); err != nil {
panic(err)
}
}
var sessionExamplePasskey *webauthn.SessionData
func saveSessionExamplePasskey(s *webauthn.SessionData) {
sessionExamplePasskey = s
}
func loadSessionExamplePasskey() (*webauthn.SessionData, error) {
if sessionExamplePasskey == nil {
return nil, fmt.Errorf("no session found")
}
return sessionExamplePasskey, nil
}
func loadUserExamplePasskey(rawID []byte, userHandle []byte) (user webauthn.User, err error) {
// Crude / Abstract example of retrieving the user for the rawID/userHandle value.
return LoadUserByHandle(userHandle)
}
func handlerExamplePasskeyCreateChallenge(w *webauthn.WebAuthn) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Crude / Abstract example of retrieving the user this registration will belong to. The user must be logged in
// for this step unless you plan to register the user and the credential at the same time i.e. usernameless.
// The user should have a unique and stable value returned from WebAuthnID that can be used to retrieve the
// account details for the user.
user, err := LoadUser()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
var (
creation *protocol.CredentialCreation
s *webauthn.SessionData
)
opts := []webauthn.RegistrationOption{
webauthn.WithResidentKeyRequirement(protocol.ResidentKeyRequirementRequired),
webauthn.WithExclusions(webauthn.Credentials(user.WebAuthnCredentials()).CredentialDescriptors()),
webauthn.WithExtensions(map[string]any{"credProps": true}),
}
if creation, s, err = w.BeginMediatedRegistration(user, protocol.MediationDefault, opts...); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude example saving the session data securely to be loaded in the finish step of the register action. This
// should be stored in such a way that the user and user agent has no access to it. For example using an opaque
// session cookie.
saveSessionExamplePasskey(s)
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(http.StatusOK)
encoder := json.NewEncoder(rw)
if err = encoder.Encode(creation); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
}
func handlerExamplePasskeyValidateCreateChallengeResponse(w *webauthn.WebAuthn) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Crude / Abstract example of retrieving the user this registration will belong to. The user must be logged in
// for this step unless you plan to register the user and the credential at the same time i.e. usernameless.
// The user should have a unique and stable value returned from WebAuthnID that can be used to retrieve the
// account details for the user.
user, err := LoadUser()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude example loading the session data securely from the start step for the register action. This should be
// loaded from a place the user and user agent has no access to it. For example using an opaque session cookie.
s, err := loadSessionExamplePasskey()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
credential, err := w.FinishRegistration(user, *s, r)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude / Abstract example of adding the credential to the list of credentials for the user. This is critical
// for performing future logins.
user.credentials = append(user.credentials, *credential)
// Crude / Abstract example of saving the updated user. This is critical for performing future logins.
if err = SaveUser(user); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(http.StatusOK)
}
}
func handlerExamplePasskeyLoginChallenge(w *webauthn.WebAuthn) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
assertion, s, err := w.BeginDiscoverableMediatedLogin(protocol.MediationDefault)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Crude example saving the session data securely to be loaded in the finish step of the login action. This
// should be stored in such a way that the user and user agent has no access to it. For example using an opaque
// session cookie.
saveSessionExamplePasskey(s)
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(http.StatusOK)
encoder := json.NewEncoder(rw)
if err = encoder.Encode(assertion); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
}
func handlerExamplePasskeyLoginChallengeResponse(w *webauthn.WebAuthn) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Crude example loading the session data securely from the start step for the login action. This should be
// loaded from a place the user and user agent has no access to it. For example using an opaque session cookie.
s, err := loadSessionExamplePasskey()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
validatedUser, validatedCredential, err := w.FinishPasskeyLogin(loadUserExamplePasskey, *s, r)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// This type assertion is necessary to perform the necessary updates.
user, ok := validatedUser.(*defaultUser)
if !ok {
rw.WriteHeader(http.StatusInternalServerError)
return
}
var found bool
// Modify the matching credential in the user struct which is critical for proper future validations as the
// metadata for this credential has been updated. No type assertion is required here since the LoadUser function
// returns the concrete implementation, you may have to adjust this if you return the abstract implementation
// instead.
for i, credential := range user.credentials {
if bytes.Equal(validatedCredential.ID, credential.ID) {
user.credentials[i] = *validatedCredential
// Crude / Abstract example of saving the user with their updated credentials. This is critical for
// proper future validations.
if err = SaveUser(user); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
found = true
break
}
}
// Should error if we can't update the credentials for the user.
if !found {
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(http.StatusOK)
}
}
Output:
Index ¶
- func CredentialParametersDefault() []protocol.CredentialParameter
- func CredentialParametersExtendedL3() []protocol.CredentialParameter
- func CredentialParametersRecommendedL3() []protocol.CredentialParameter
- func SelectAuthenticator(att string, rrk *bool, uv string) protocol.AuthenticatorSelection
- type Authenticator
- type Config
- type ConfigProvider
- type Credential
- type CredentialAttestation
- type CredentialFlags
- type Credentials
- type DiscoverableUserHandler
- type LoginOption
- func WithAllowedCredentials(allowList []protocol.CredentialDescriptor) LoginOption
- func WithAppIdExtension(appid string) LoginOption
- func WithAssertionExtensions(extensions protocol.AuthenticationExtensions) LoginOption
- func WithAssertionPublicKeyCredentialHints(hints []protocol.PublicKeyCredentialHints) LoginOption
- func WithChallenge(challenge []byte) LoginOption
- func WithLoginRelyingPartyID(id string) LoginOption
- func WithUserVerification(userVerification protocol.UserVerificationRequirement) LoginOption
- type RegistrationOption
- func WithAppIdExcludeExtension(appid string) RegistrationOption
- func WithAttestationFormats(formats []protocol.AttestationFormat) RegistrationOption
- func WithAuthenticatorSelection(authenticatorSelection protocol.AuthenticatorSelection) RegistrationOption
- func WithConveyancePreference(preference protocol.ConveyancePreference) RegistrationOption
- func WithCredentialParameters(credentialParams []protocol.CredentialParameter) RegistrationOption
- func WithExclusions(excludeList []protocol.CredentialDescriptor) RegistrationOption
- func WithExtensions(extension protocol.AuthenticationExtensions) RegistrationOption
- func WithPublicKeyCredentialHints(hints []protocol.PublicKeyCredentialHints) RegistrationOption
- func WithRegistrationRelyingPartyID(id string) RegistrationOption
- func WithRegistrationRelyingPartyName(name string) RegistrationOption
- func WithResidentKeyRequirement(requirement protocol.ResidentKeyRequirement) RegistrationOption
- type SessionData
- type TimeoutConfig
- type TimeoutsConfig
- type User
- type WebAuthn
- func (webauthn *WebAuthn) BeginDiscoverableLogin(opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)
- func (webauthn *WebAuthn) BeginDiscoverableMediatedLogin(mediation protocol.CredentialMediationRequirement, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)
- func (webauthn *WebAuthn) BeginLogin(user User, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)
- func (webauthn *WebAuthn) BeginMediatedLogin(user User, mediation protocol.CredentialMediationRequirement, ...) (*protocol.CredentialAssertion, *SessionData, error)
- func (webauthn *WebAuthn) BeginMediatedRegistration(user User, mediation protocol.CredentialMediationRequirement, ...) (creation *protocol.CredentialCreation, session *SessionData, err error)
- func (webauthn *WebAuthn) BeginRegistration(user User, opts ...RegistrationOption) (creation *protocol.CredentialCreation, session *SessionData, err error)
- func (webauthn *WebAuthn) CreateCredential(user User, session SessionData, ...) (credential *Credential, err error)
- func (webauthn *WebAuthn) FinishDiscoverableLogin(handler DiscoverableUserHandler, session SessionData, response *http.Request) (credential *Credential, err error)
- func (webauthn *WebAuthn) FinishLogin(user User, session SessionData, response *http.Request) (credential *Credential, err error)
- func (webauthn *WebAuthn) FinishPasskeyLogin(handler DiscoverableUserHandler, session SessionData, response *http.Request) (user User, credential *Credential, err error)
- func (webauthn *WebAuthn) FinishRegistration(user User, session SessionData, request *http.Request) (credential *Credential, err error)
- func (webauthn *WebAuthn) ValidateDiscoverableLogin(handler DiscoverableUserHandler, session SessionData, ...) (credential *Credential, err error)
- func (webauthn *WebAuthn) ValidateLogin(user User, session SessionData, ...) (credential *Credential, err error)
- func (webauthn *WebAuthn) ValidatePasskeyLogin(handler DiscoverableUserHandler, session SessionData, ...) (user User, credential *Credential, err error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CredentialParametersDefault ¶ added in v0.12.0
func CredentialParametersDefault() []protocol.CredentialParameter
CredentialParametersDefault returns the default list of acceptable credential algorithms. This includes ES256, ES384, ES512, RS256, RS384, RS512, PS256, PS384, PS512, and EdDSA. The order indicates preference.
func CredentialParametersExtendedL3 ¶ added in v0.12.0
func CredentialParametersExtendedL3() []protocol.CredentialParameter
CredentialParametersExtendedL3 returns the WebAuthn Level 3 recommended credential algorithm list (EdDSA, ES256, RS256) extended with all other algorithms supported by this library (ES384, ES512, RS384, RS512, PS256, PS384, PS512). The Level 3 recommended algorithms appear first to indicate preference.
func CredentialParametersRecommendedL3 ¶ added in v0.12.0
func CredentialParametersRecommendedL3() []protocol.CredentialParameter
CredentialParametersRecommendedL3 returns the WebAuthn Level 3 recommended credential algorithm list: EdDSA, ES256, and RS256 (in that order). This is the minimal set recommended by the specification for broad authenticator compatibility.
func SelectAuthenticator ¶
func SelectAuthenticator(att string, rrk *bool, uv string) protocol.AuthenticatorSelection
SelectAuthenticator is a convenience function that constructs a protocol.AuthenticatorSelection from individual string and boolean parameters. Use protocol.ResidentKeyRequired or protocol.ResidentKeyNotRequired for the rrk parameter.
Types ¶
type Authenticator ¶
type Authenticator struct {
// The AAGUID of the authenticator. An AAGUID is defined as an array containing the globally unique
// identifier of the authenticator model being sought.
AAGUID []byte `json:"AAGUID"`
// SignCount is a representation of the number of times the Authenticator or Credential have been used to login.
// Upon a new login operation, the Relying Party compares the stored signature counter value with the new SignCount
// value returned in the assertion’s authenticator data. If this new SignCount value is less than or equal to the
// stored value, a cloned authenticator may exist, or the authenticator may be malfunctioning.
SignCount uint32 `json:"signCount"`
// CloneWarning is a signal that the authenticator may be cloned, i.e. at least two copies of the
// credential private key may exist and are being used in parallel. Relying Parties should incorporate
// this information into their risk scoring. Whether the Relying Party updates the stored signature
// counter value in this case, or not, or fails the authentication ceremony or not, is Relying Party-specific.
CloneWarning bool `json:"cloneWarning"`
// Attachment is the authenticatorAttachment value returned by the request.
Attachment protocol.AuthenticatorAttachment `json:"attachment"`
}
Authenticator represents a specific authenticator in the context of a Credential.
func (*Authenticator) UpdateCounter ¶
func (a *Authenticator) UpdateCounter(authDataCount uint32)
UpdateCounter updates the authenticator and either sets the clone warning value or the sign count.
Step 17 of §7.2. about verifying attestation. If the signature counter value authData.signCount is nonzero or the value stored in conjunction with credential’s id attribute is nonzero, then run the following sub-step:
If the signature counter value authData.signCount is → Greater than the signature counter value stored in conjunction with credential’s id attribute. Update the stored signature counter value, associated with credential’s id attribute, to be the value of authData.signCount. → Less than or equal to the signature counter value stored in conjunction with credential’s id attribute. This is a signal that the authenticator may be cloned, see CloneWarning above for more information.
type Config ¶
type Config struct {
// RPID configures the Relying Party Server ID. This should generally be the origin without a scheme and port.
RPID string
// RPDisplayName configures the display name for the Relying Party Server. This can be any string.
RPDisplayName string
// RPOrigins configures the list of Relying Party Server Origins that are permitted. The provided origins can either
// be fully qualified origins or strings for simple string comparison. The strings are matched using canonical
// origin matching semantics specifically if they start with 'http://' or 'https://' if the provided origin has a
// case-insensitive equal scheme and host component they are equal, otherwise simple string comparison is utilized
// to determine equality.
RPOrigins []string
// RPTopOrigins configures the list of Relying Party Server Top Origins that are permitted. The provided origins can
// either be fully qualified origins or strings for simple string comparison. The strings are matched using
// canonical origin matching semantics specifically if they start with 'http://' or 'https://' if the provided
// origin has a case-insensitive equal scheme and host component they are equal, otherwise simple string comparison
// is utilized to determine equality.
RPTopOrigins []string
// RPTopOriginVerificationMode determines the verification mode for the Top Origin value. By default the
// TopOriginIgnoreVerificationMode is used however this is going to change at such a time as WebAuthn Level 3
// becomes recommended, implementers should explicitly set this value if they want stability.
RPTopOriginVerificationMode protocol.TopOriginVerificationMode
// AttestationPreference sets the default attestation conveyance preferences.
AttestationPreference protocol.ConveyancePreference
// AuthenticatorSelection sets the default authenticator selection options.
AuthenticatorSelection protocol.AuthenticatorSelection
// Debug enables various debug options.
Debug bool
// EncodeUserIDAsString ensures the user.id value during registrations is encoded as a raw UTF8 string. This is
// useful when you only use printable ASCII characters for the random user.id but the browser library does not
// decode the URL Safe Base64 data.
EncodeUserIDAsString bool
// Timeouts configures various timeouts.
Timeouts TimeoutsConfig
// MDS configures a FIDO Metadata Service provider for authenticator trust validation. When set, the library
// validates attestation statements against known authenticator metadata including trust anchors, attestation
// types, and authenticator status. Use the providers in [github.com/go-webauthn/webauthn/metadata/providers/memory]
// or [github.com/go-webauthn/webauthn/metadata/providers/cached] to create a provider instance.
MDS metadata.Provider
// contains filtered or unexported fields
}
Config represents the Relying Party configuration for WebAuthn operations. At minimum, RPID and RPOrigins must be configured. The RPID should be the effective domain of the Relying Party (e.g. "example.com") and RPOrigins should contain the fully qualified origins that are permitted (e.g. "https://example.com").
func (*Config) GetMetaDataProvider ¶ added in v0.11.0
GetMetaDataProvider returns the configured FIDO Metadata Service provider.
func (*Config) GetOrigins ¶ added in v0.11.0
GetOrigins returns the configured Relying Party Origins.
func (*Config) GetTopOriginVerificationMode ¶ added in v0.11.0
func (c *Config) GetTopOriginVerificationMode() protocol.TopOriginVerificationMode
GetTopOriginVerificationMode returns the configured Top Origin verification mode.
func (*Config) GetTopOrigins ¶ added in v0.11.0
GetTopOrigins returns the configured Relying Party Top Origins.
type ConfigProvider ¶ added in v0.11.0
type ConfigProvider interface {
GetRPID() string
GetOrigins() []string
GetTopOrigins() []string
GetTopOriginVerificationMode() protocol.TopOriginVerificationMode
GetMetaDataProvider() metadata.Provider
}
ConfigProvider is an interface that provides access to the WebAuthn Config values. This is useful for implementations that wish to provide configuration from alternative sources.
type Credential ¶
type Credential struct {
// The ID is the ID of the public key credential source. Described by the Credential Record 'id' field.
ID []byte `json:"id"`
// The credential public key of the public key credential source. Described by the Credential Record 'publicKey'
// field.
PublicKey []byte `json:"publicKey"`
// The AttestationType stores the attestation format used (if any) by the authenticator when creating the
// Credential.
//
// Important Note: This field is named attestationType but this is actually the attestation format.
AttestationType string `json:"attestationType"`
// Transport types the authenticator supports. Described by the Credential Record 'transports' field.
Transport []protocol.AuthenticatorTransport `json:"transport"`
// Flags represent the commonly stored flags.
Flags CredentialFlags `json:"flags"`
// The Authenticator information for a given Credential.
Authenticator Authenticator `json:"authenticator"`
// The attestation values that can be used to validate this Credential via the MDS3 at a later date.
Attestation CredentialAttestation `json:"attestation"`
}
Credential contains all needed information about a WebAuthn credential for storage. This struct is effectively the Credential Record as described in the specification.
Provided this data structure is preserved properly, a Credential can be verified against the FIDO Metadata Service at a later date using the Credential.Verify method with a metadata.Provider.
It is strongly recommended for the best security that a Credential is encrypted at rest with the exception of the ID and the value you use to lookup the user. This prevents a person with access to the database being able to compromise privacy by being able to view this data, as well as prevents them being able to compromise security by adding or modifying a Credential without them also having access to the encryption key.
See: §4. Terminology: Credential Record (https://www.w3.org/TR/webauthn-3/#credential-record)
func NewCredential ¶ added in v0.11.0
func NewCredential(clientDataHash []byte, c *protocol.ParsedCredentialCreationData) (credential *Credential, err error)
NewCredential returns a *Credential from a successfully validated registration response. The returned Credential includes a populated CredentialAttestation containing the raw attestation data needed for future verification; see the CredentialAttestation documentation for why these values must be persisted.
func (Credential) Descriptor ¶ added in v0.2.0
func (c Credential) Descriptor() (descriptor protocol.CredentialDescriptor)
Descriptor converts a Credential into a protocol.CredentialDescriptor.
func (Credential) SignalUnknownCredential ¶ added in v0.16.0
func (c Credential) SignalUnknownCredential(rpid string) *protocol.SignalUnknownCredential
SignalUnknownCredential creates a struct that can easily be marshaled to JSON which indicates this is an unknown Credential.
type CredentialAttestation ¶ added in v0.11.0
type CredentialAttestation struct {
// ClientDataJSON is the raw JSON-encoded client data from the registration response. This is the verbatim value
// provided by the client and is used to recompute the client data hash during later verification.
ClientDataJSON []byte `json:"clientDataJSON"`
// ClientDataHash is the SHA-256 hash of ClientDataJSON computed during registration verification. If empty,
// [Credential.Verify] will recompute it from ClientDataJSON.
ClientDataHash []byte `json:"clientDataHash"`
// AuthenticatorData is the raw authenticator data from the registration response as provided in the
// RegistrationResponseJSON. This is the unparsed byte representation that can be re-parsed for future validation.
AuthenticatorData []byte `json:"authenticatorData"`
// PublicKeyAlgorithm is the COSE algorithm identifier for the credential's public key.
PublicKeyAlgorithm int64 `json:"publicKeyAlgorithm"`
// Object is the raw CBOR-encoded attestation object from the registration response. This contains the attestation
// statement, format, and authenticator data needed by [Credential.Verify] to re-perform attestation verification.
Object []byte `json:"object"`
}
CredentialAttestation holds the raw attestation data from a registration ceremony. These values are intentionally stored in their original unparsed form rather than as parsed structures. This is critical because:
- It enables the Credential to be verified against the FIDO Metadata Service at a later date using Credential.Verify, even long after the registration ceremony has completed.
- The WebAuthn specification evolves over time, introducing new validation procedures. Preserving the raw data ensures that credentials created today can be re-validated against future rules without requiring re-registration.
- Raw data serves as an auditable record of exactly what the authenticator and client provided during registration, independent of how the library parsed it at that point in time.
Implementers MUST persist all fields of this struct. Omitting any field may prevent future verification.
type CredentialFlags ¶ added in v0.7.2
type CredentialFlags struct {
// Flag UP indicates the users presence.
UserPresent bool `json:"userPresent"`
// Flag UV indicates the user performed verification.
UserVerified bool `json:"userVerified"`
// Flag BE indicates the credential is able to be backed up and/or sync'd between devices. This should NEVER change.
BackupEligible bool `json:"backupEligible"`
// Flag BS indicates the credential has been backed up and/or sync'd. This value can change but it's recommended
// that RP's keep track of this value.
BackupState bool `json:"backupState"`
// contains filtered or unexported fields
}
CredentialFlags contains the boolean flags derived from the authenticator data during registration or login. These flags indicate the state of user presence, user verification, and backup eligibility/state at the time the credential was used.
func NewCredentialFlags ¶ added in v0.12.0
func NewCredentialFlags(flags protocol.AuthenticatorFlags) CredentialFlags
NewCredentialFlags is a utility function that is used to derive the Credential's Flags field given a protocol.AuthenticatorFlags. This allows implementers to solely save the Raw field of the CredentialFlags to restore them appropriately for appropriate processing without concern that changes forced upon implementers by the W3C will introduce breaking changes.
func (CredentialFlags) ProtocolValue ¶ added in v0.12.0
func (f CredentialFlags) ProtocolValue() protocol.AuthenticatorFlags
ProtocolValue returns the underlying protocol.AuthenticatorFlags provided this CredentialFlags was created using NewCredentialFlags.
type Credentials ¶ added in v0.13.3
type Credentials []Credential
Credentials is a decorator type which allows easily converting a Credential slice into a protocol.CredentialDescriptor slice by utilizing the Credentials.CredentialDescriptors method. This will be the type used globally for the library in a future release.
func (Credentials) CredentialDescriptors ¶ added in v0.13.3
func (c Credentials) CredentialDescriptors() (descriptors []protocol.CredentialDescriptor)
CredentialDescriptors returns the protocol.CredentialDescriptor slice for this Credentials type.
type DiscoverableUserHandler ¶ added in v0.2.0
DiscoverableUserHandler is a callback function that the Relying Party must provide when performing a discoverable (passkey) login. It is called with the rawID of the credential and the userHandle from the authenticator response, and must return the User who owns the credential. This is necessary because in discoverable login flows, the Relying Party does not know which user is authenticating until the authenticator response is received.
type LoginOption ¶
type LoginOption func(*protocol.PublicKeyCredentialRequestOptions)
LoginOption is a functional option that modifies the protocol.PublicKeyCredentialRequestOptions sent to the client during a login ceremony. Use the With* functions in this package (e.g. WithUserVerification, WithAllowedCredentials) to create login options.
func WithAllowedCredentials ¶
func WithAllowedCredentials(allowList []protocol.CredentialDescriptor) LoginOption
WithAllowedCredentials adjusts the allowed credentials via a slice of protocol.CredentialDescriptor values, discussed in the included specification sections with user-supplied values.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials)
Specification: §5.10.3. Credential Descriptor (https://www.w3.org/TR/webauthn/#dictdef-publickeycredentialdescriptor)
func WithAppIdExtension ¶ added in v0.2.0
func WithAppIdExtension(appid string) LoginOption
WithAppIdExtension automatically includes the specified appid if the AllowedCredentials contains a credential with the type `fido-u2f`.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialrequestoptions-extensions)
func WithAssertionExtensions ¶
func WithAssertionExtensions(extensions protocol.AuthenticationExtensions) LoginOption
WithAssertionExtensions adjusts the requested extensions by providing a protocol.AuthenticationExtensions.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialrequestoptions-extensions)
func WithAssertionPublicKeyCredentialHints ¶ added in v0.11.0
func WithAssertionPublicKeyCredentialHints(hints []protocol.PublicKeyCredentialHints) LoginOption
WithAssertionPublicKeyCredentialHints adjusts the non-default hints for credential types to select during login by providing a slice of protocol.PublicKeyCredentialHints.
WebAuthn Level 3.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-hints)
func WithChallenge ¶ added in v0.12.0
func WithChallenge(challenge []byte) LoginOption
WithChallenge overrides the default random challenge with a user supplied value. In order to prevent replay attacks, the challenges MUST contain enough entropy to make guessing them infeasible. Challenges SHOULD therefore be at least 16 bytes long. This function is EXPERIMENTAL and can be removed without warning.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialrequestoptions-challenge)
Specification: §13.4.3. Cryptographic Challenges (https://www.w3.org/TR/webauthn/#sctn-cryptographic-challenges)
func WithLoginRelyingPartyID ¶ added in v0.11.0
func WithLoginRelyingPartyID(id string) LoginOption
WithLoginRelyingPartyID sets the Relying Party ID for this particular login.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialrequestoptions-rpid)
func WithUserVerification ¶
func WithUserVerification(userVerification protocol.UserVerificationRequirement) LoginOption
WithUserVerification adjusts the user verification preference by providing a protocol.UserVerificationRequirement.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialrequestoptions-userverification)
type RegistrationOption ¶
type RegistrationOption func(*protocol.PublicKeyCredentialCreationOptions)
RegistrationOption is a functional option that modifies the protocol.PublicKeyCredentialCreationOptions sent to the client during a registration ceremony. Use the With* functions in this package (e.g. WithConveyancePreference, WithExclusions, WithAuthenticatorSelection) to create registration options.
func WithAppIdExcludeExtension ¶ added in v0.2.0
func WithAppIdExcludeExtension(appid string) RegistrationOption
WithAppIdExcludeExtension automatically includes the specified appid if the CredentialExcludeList contains a credential with the type `fido-u2f`.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialcreationoptions-extensions)
Specification: §9. Extensions (https://www.w3.org/TR/webauthn/#webauthn-extensions)
Specification: §10.1.2. FIDO AppID Exclusion Extension (https://www.w3.org/TR/webauthn/#sctn-appid-exclude-extension)
func WithAttestationFormats ¶ added in v0.11.0
func WithAttestationFormats(formats []protocol.AttestationFormat) RegistrationOption
WithAttestationFormats adjusts the non-default formats for credential types to select during registration.
WebAuthn Level 3.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialcreationoptions-attestationformats)
func WithAuthenticatorSelection ¶
func WithAuthenticatorSelection(authenticatorSelection protocol.AuthenticatorSelection) RegistrationOption
WithAuthenticatorSelection adjusts the non-default parameters regarding the authenticator to select during registration.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection)
Specification: §5.4.4. Authenticator Selection Criteria (https://www.w3.org/TR/webauthn/#dictdef-authenticatorselectioncriteria)
func WithConveyancePreference ¶
func WithConveyancePreference(preference protocol.ConveyancePreference) RegistrationOption
WithConveyancePreference adjusts the non-default parameters regarding whether the authenticator should attest to the credential.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialcreationoptions-attestation)
func WithCredentialParameters ¶ added in v0.3.4
func WithCredentialParameters(credentialParams []protocol.CredentialParameter) RegistrationOption
WithCredentialParameters adjusts the credential parameters in the registration options.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams)
func WithExclusions ¶
func WithExclusions(excludeList []protocol.CredentialDescriptor) RegistrationOption
WithExclusions adjusts the non-default parameters regarding credentials to exclude from registration.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials)
func WithExtensions ¶
func WithExtensions(extension protocol.AuthenticationExtensions) RegistrationOption
WithExtensions adjusts the extension parameter in the registration options.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialcreationoptions-extensions)
Specification: §9. Extensions (https://www.w3.org/TR/webauthn/#webauthn-extensions)
func WithPublicKeyCredentialHints ¶ added in v0.11.0
func WithPublicKeyCredentialHints(hints []protocol.PublicKeyCredentialHints) RegistrationOption
WithPublicKeyCredentialHints adjusts the non-default hints for credential types to select during registration.
WebAuthn Level 3.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialcreationoptions-hints)
func WithRegistrationRelyingPartyID ¶ added in v0.11.0
func WithRegistrationRelyingPartyID(id string) RegistrationOption
WithRegistrationRelyingPartyID sets the relying party id for the registration.
func WithRegistrationRelyingPartyName ¶ added in v0.11.0
func WithRegistrationRelyingPartyName(name string) RegistrationOption
WithRegistrationRelyingPartyName sets the relying party name for the registration.
func WithResidentKeyRequirement ¶ added in v0.2.0
func WithResidentKeyRequirement(requirement protocol.ResidentKeyRequirement) RegistrationOption
WithResidentKeyRequirement sets both the resident key and require resident key protocol options.
Specification: §5.4. Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection)
Specification: §5.4.4. Authenticator Selection Criteria (https://www.w3.org/TR/webauthn/#dictdef-authenticatorselectioncriteria)
type SessionData ¶
type SessionData struct {
Challenge string `json:"challenge" msg:"c"`
RelyingPartyID string `json:"rpId" msg:"r"`
UserID []byte `json:"user_id" msg:"u"`
AllowedCredentialIDs [][]byte `json:"allowed_credentials,omitempty" msg:"allow"`
Expires time.Time `json:"expires" msg:"exp"`
UserVerification protocol.UserVerificationRequirement `json:"userVerification" msg:"uv"`
Extensions protocol.AuthenticationExtensions `json:"extensions,omitempty" msg:"exts"`
CredParams []protocol.CredentialParameter `json:"credParams,omitempty" msg:"params"`
Mediation protocol.CredentialMediationRequirement `json:"mediation,omitempty" msg:"cmr"`
}
SessionData is the data that must be stored by the Relying Party between the Begin and Finish steps of a WebAuthn ceremony. It contains the challenge and other parameters needed to verify the authenticator's response.
The Relying Party must store this data securely and associate it with the user's session. It should not be modifiable by the client (e.g. store it server-side or in a signed, opaque cookie). After the ceremony completes, the session data should be discarded.
func (*SessionData) DecodeMsg ¶ added in v0.16.2
func (z *SessionData) DecodeMsg(dc *msgp.Reader) (err error)
DecodeMsg implements msgp.Decodable
func (*SessionData) EncodeMsg ¶ added in v0.16.2
func (z *SessionData) EncodeMsg(en *msgp.Writer) (err error)
EncodeMsg implements msgp.Encodable
func (*SessionData) MarshalMsg ¶ added in v0.16.2
func (z *SessionData) MarshalMsg(b []byte) (o []byte, err error)
MarshalMsg implements msgp.Marshaler
func (*SessionData) Msgsize ¶ added in v0.16.2
func (z *SessionData) Msgsize() (s int)
Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message
func (*SessionData) UnmarshalMsg ¶ added in v0.16.2
func (z *SessionData) UnmarshalMsg(bts []byte) (o []byte, err error)
UnmarshalMsg implements msgp.Unmarshaler
type TimeoutConfig ¶ added in v0.8.0
type TimeoutConfig struct {
// Enforce the timeouts at the Relying Party / Server. This means if enabled and the user takes too long that even
// if the browser does not enforce the timeout the Relying Party / Server will.
Enforce bool
// Timeout is the timeout for logins/registrations when the UserVerificationRequirement is set to anything other
// than discouraged.
Timeout time.Duration
// TimeoutUVD is the timeout for logins/registrations when the UserVerificationRequirement is set to discouraged.
TimeoutUVD time.Duration
}
TimeoutConfig configures timeout behavior for a specific WebAuthn ceremony (registration or login).
type TimeoutsConfig ¶ added in v0.8.0
type TimeoutsConfig struct {
Login TimeoutConfig
Registration TimeoutConfig
}
TimeoutsConfig configures the timeout durations for both login and registration ceremonies. These values are sent to the client as the timeout field in the credential request/creation options and optionally enforced server-side.
type User ¶
type User interface {
// WebAuthnID provides the user handle of the user account. A user handle is an opaque byte sequence with a maximum
// size of 64 bytes, and is not meant to be displayed to the user.
//
// To ensure secure operation, authentication and authorization decisions MUST be made on the basis of this id
// member, not the displayName nor name members. See Section 6.1 of [RFC8266].
//
// It's recommended this value is completely random and uses the entire 64 bytes.
//
// Specification: §5.4.3. User Account Parameters for Credential Generation (https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id)
WebAuthnID() []byte
// WebAuthnName provides the name attribute of the user account during registration and is a human-palatable name
// for the user account, intended only for display. For example, "Alex Müller" or "田中倫". The Relying Party SHOULD
// let the user choose this, and SHOULD NOT restrict the choice more than necessary.
//
// Specification: §5.4.3. User Account Parameters for Credential Generation (https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentity)
WebAuthnName() string
// WebAuthnDisplayName provides the name attribute of the user account during registration and is a human-palatable
// name for the user account, intended only for display. For example, "Alex Müller" or "田中倫". The Relying Party
// SHOULD let the user choose this, and SHOULD NOT restrict the choice more than necessary.
//
// Specification: §5.4.3. User Account Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialuserentity-displayname)
WebAuthnDisplayName() string
// WebAuthnCredentials provides the slice of [Credential] objects owned by the user. This generally should be all
// the [Credential] objects owned by the user regardless of which flow is being used.
WebAuthnCredentials() []Credential
}
User is an interface with the Relying Party's User entry and provides the fields and methods needed for WebAuthn registration operations.
type WebAuthn ¶
type WebAuthn struct {
Config *Config
}
WebAuthn is the primary interface of this package. It provides methods to begin and finish both registration and login ceremonies. Create an instance using New and then call the appropriate Begin/Finish methods for your use case. See the package documentation for detailed ceremony flows.
func New ¶
New creates a new WebAuthn instance from the provided Config. The configuration is validated before the instance is returned.
func (*WebAuthn) BeginDiscoverableLogin ¶ added in v0.2.0
func (webauthn *WebAuthn) BeginDiscoverableLogin(opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)
BeginDiscoverableLogin creates the *protocol.CredentialAssertion data payload that should be sent to the user agent for beginning the login/assertion process. This function is used to perform a client-side discoverable login when the identity of the user is not known such as passwordless or usernameless authentication, to specify a conditional mediation requirement use WebAuthn.BeginDiscoverableMediatedLogin, to perform logins where the identity of the user is known such as multifactor authentication see WebAuthn.BeginLogin and WebAuthn.BeginMediatedLogin instead. The format of this data can be seen in §5.5 of the WebAuthn specification. These default values can be amended by providing additional LoginOption parameters. This function also returns SessionData, that must be stored by the RP in a secure manner and then provided to the WebAuthn.FinishLogin function. This data helps us verify the ownership of the credential being retrieved.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dictionary-assertion-options)
func (*WebAuthn) BeginDiscoverableMediatedLogin ¶ added in v0.12.0
func (webauthn *WebAuthn) BeginDiscoverableMediatedLogin(mediation protocol.CredentialMediationRequirement, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)
BeginDiscoverableMediatedLogin is similar to WebAuthn.BeginDiscoverableLogin however it also allows specifying a credential mediation requirement.
func (*WebAuthn) BeginLogin ¶
func (webauthn *WebAuthn) BeginLogin(user User, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)
BeginLogin creates the *protocol.CredentialAssertion data payload that should be sent to the user agent for beginning the login/assertion process. This function is used to perform a login when the identity of the user is known such as multifactor authentications, to specify a conditional mediation requirement use WebAuthn.BeginMediatedLogin, to perform a login when the identity of the user is not known see WebAuthn.BeginDiscoverableLogin and WebAuthn.BeginDiscoverableMediatedLogin instead. The format of this data can be seen in §5.5 of the WebAuthn specification. These default values can be amended by providing additional LoginOption parameters. This function also returns SessionData, that must be stored by the RP in a secure manner and then provided to the WebAuthn.FinishLogin function. This data helps us verify the ownership of the credential being retrieved.
Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dictionary-assertion-options)
func (*WebAuthn) BeginMediatedLogin ¶ added in v0.12.0
func (webauthn *WebAuthn) BeginMediatedLogin(user User, mediation protocol.CredentialMediationRequirement, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)
BeginMediatedLogin is similar to WebAuthn.BeginLogin however it also allows specifying a credential mediation requirement.
func (*WebAuthn) BeginMediatedRegistration ¶ added in v0.12.0
func (webauthn *WebAuthn) BeginMediatedRegistration(user User, mediation protocol.CredentialMediationRequirement, opts ...RegistrationOption) (creation *protocol.CredentialCreation, session *SessionData, err error)
BeginMediatedRegistration is similar to WebAuthn.BeginRegistration however it also allows specifying a credential mediation requirement.
func (*WebAuthn) BeginRegistration ¶
func (webauthn *WebAuthn) BeginRegistration(user User, opts ...RegistrationOption) (creation *protocol.CredentialCreation, session *SessionData, err error)
BeginRegistration generates a new set of registration data to be sent to the client and authenticator. To set a conditional mediation requirement for the registration see WebAuthn.BeginMediatedRegistration.
func (*WebAuthn) CreateCredential ¶
func (webauthn *WebAuthn) CreateCredential(user User, session SessionData, parsedResponse *protocol.ParsedCredentialCreationData) (credential *Credential, err error)
CreateCredential verifies a parsed response against the user's credentials and session data.
If you wish to skip performing the step required to parse the *protocol.ParsedCredentialCreationData and you're using net/http then you can use WebAuthn.FinishRegistration instead.
func (*WebAuthn) FinishDiscoverableLogin ¶ added in v0.9.0
func (webauthn *WebAuthn) FinishDiscoverableLogin(handler DiscoverableUserHandler, session SessionData, response *http.Request) (credential *Credential, err error)
FinishDiscoverableLogin takes the response from the client and validates it against the handler and stored session data. The handler helps to find out which user must be used to validate the response. This is a function defined in your business code that will retrieve the user from your persistent data.
As with all Finish functions, this function requires a *http.Request but you can perform the same steps with the protocol.ParseCredentialRequestResponseBody or protocol.ParseCredentialRequestResponseBytes which require an io.Reader or byte array respectively, you can also use an arbitrary *protocol.ParsedCredentialAssertionData which is returned from all of these functions i.e. by implementing a custom parser. The DiscoverableUserHandler, *SessionData, and *protocol.ParsedCredentialAssertionData can then be used with the WebAuthn.ValidatePasskeyLogin function.
This function will return the protocol.ErrorUnknownCredential error type when the User returned by the handler does not contain a Credential with the same ID byte array provided all Credential's in the SessionData exist in the User's Credential list.
func (*WebAuthn) FinishLogin ¶
func (webauthn *WebAuthn) FinishLogin(user User, session SessionData, response *http.Request) (credential *Credential, err error)
FinishLogin takes the response from the client and validates it against the user credentials and stored session data.
As with all Finish functions, this function requires a *http.Request but you can perform the same steps with the protocol.ParseCredentialRequestResponseBody or protocol.ParseCredentialRequestResponseBytes which require an io.Reader or byte array respectively, you can also use an arbitrary *protocol.ParsedCredentialAssertionData which is returned from all of these functions i.e. by implementing a custom parser. The *SessionData, and *protocol.ParsedCredentialAssertionData can then be used with the WebAuthn.ValidateLogin function.
This function will return the protocol.ErrorUnknownCredential error type when the User provided does not contain a Credential with the same ID byte array provided all Credential's in the SessionData exist in the User's Credential list.
func (*WebAuthn) FinishPasskeyLogin ¶ added in v0.13.2
func (webauthn *WebAuthn) FinishPasskeyLogin(handler DiscoverableUserHandler, session SessionData, response *http.Request) (user User, credential *Credential, err error)
FinishPasskeyLogin takes the response from the client and validate it against the handler and stored session data. The handler helps to find out which user must be used to validate the response. This is a function defined in your business code that will retrieve the user from your persistent data.
As with all Finish functions this function requires a *http.Request but you can perform the same steps with the protocol.ParseCredentialRequestResponseBody or protocol.ParseCredentialRequestResponseBytes which require an io.Reader or byte array respectively, you can also use an arbitrary *protocol.ParsedCredentialAssertionData which is returned from all of these functions i.e. by implementing a custom parser. The DiscoverableUserHandler, *SessionData, and *protocol.ParsedCredentialAssertionData can then be used with the WebAuthn.ValidatePasskeyLogin function.
This function will return the protocol.ErrorUnknownCredential error type when the User returned by the handler does not contain a Credential with the same ID byte array provided all Credential's in the SessionData exist in the User's Credential list.
func (*WebAuthn) FinishRegistration ¶
func (webauthn *WebAuthn) FinishRegistration(user User, session SessionData, request *http.Request) (credential *Credential, err error)
FinishRegistration takes the response from the authenticator and client and verify the credential against the user's credentials and session data.
As with all Finish functions this function requires a *http.Request but you can perform the same steps with the protocol.ParseCredentialCreationResponseBody or protocol.ParseCredentialCreationResponseBytes which require an io.Reader or byte array respectively, you can also use an arbitrary *protocol.ParsedCredentialCreationData which is returned from all of these functions i.e. by implementing a custom parser. The User, *SessionData, and *protocol.ParsedCredentialCreationData can then be used with the WebAuthn.CreateCredential function.
func (*WebAuthn) ValidateDiscoverableLogin ¶ added in v0.2.0
func (webauthn *WebAuthn) ValidateDiscoverableLogin(handler DiscoverableUserHandler, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (credential *Credential, err error)
ValidateDiscoverableLogin is similar to WebAuthn.ValidateLogin that allows for discoverable credentials. It's recommended that WebAuthn.ValidatePasskeyLogin is used instead.
If you wish to skip performing the step required to parse the *protocol.ParsedCredentialAssertionData and you're using net/http then you can use WebAuthn.FinishDiscoverableLogin instead.
This function will return the protocol.ErrorUnknownCredential error type when the User returned by the handler does not contain a Credential with the same ID byte array provided all Credential's in the SessionData exist in the User's Credential list.
Note: this is just a backwards compatibility layer over WebAuthn.ValidatePasskeyLogin which returns more information.
func (*WebAuthn) ValidateLogin ¶
func (webauthn *WebAuthn) ValidateLogin(user User, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (credential *Credential, err error)
ValidateLogin takes a parsed response and validates it against the user credentials and session data.
If you wish to skip performing the step required to parse the *protocol.ParsedCredentialAssertionData and you're using net/http then you can use WebAuthn.FinishLogin instead.
This function will return the protocol.ErrorUnknownCredential error type when the User provided does not contain a Credential with the same ID byte array provided all Credential's in the SessionData exist in the User's Credential list.
func (*WebAuthn) ValidatePasskeyLogin ¶ added in v0.11.0
func (webauthn *WebAuthn) ValidatePasskeyLogin(handler DiscoverableUserHandler, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (user User, credential *Credential, err error)
ValidatePasskeyLogin is similar to WebAuthn.ValidateLogin that allows for discoverable credentials.
If you wish to skip performing the step required to parse the *protocol.ParsedCredentialAssertionData and you're using net/http then you can use WebAuthn.FinishPasskeyLogin instead.
This function will return the protocol.ErrorUnknownCredential error type when the User returned by the handler does not contain a Credential with the same ID byte array provided all Credential's in the SessionData exist in the User's Credential list.