Documentation ¶
Overview ¶
Package authentication provides a client for using the Auth0 Authentication API.
Usage ¶
import ( "github.com/auth0/go-auth0" "github.com/auth0/go-auth0/authentication" "github.com/auth0/go-auth0/authentication/database" "github.com/auth0/go-auth0/authentication/oauth" ) a, err := authentication.New( context.TODO(), domain, authentication.WithClientID(id), authentication.WithClientSecret(secret), // Optional depending on the grants used ) if err != nil { // handle err } // Now we have an authentication client, we can interact with the Auth0 Authentication API. // Sign up a user userData := database.SignupRequest{ Connection: "Username-Password-Authentication", Username: "mytestaccount", Password: "mypassword", Email: "mytestaccount@example.com", } createdUser, err := a.Database.Signup(context.TODO(), userData) if err != nil { // handle err } // Login using OAuth grants tokenSet, err := a.OAuth.LoginWithAuthCodeWithPKCE(context.TODO(), oauth.LoginWithAuthCodeWithPKCERequest{ Code: "test-code", CodeVerifier: "test-code-verifier", }, oauth.IDTokenValidationOptionalVerification{}) if err != nil { // handle err }
Configuration ¶
There are several options that can be specified during the creation of a client. For a complete list see Option.
a, err := authentication.New( context.TODO(), domain, authentication.WithClientID(id), authentication.WithClientSecret(secret), // Optional depending on the grants used authentication.WithClockTolerance(10 * time.Second), )
Handling Errors ¶
This package exports an authentication.Error type that can be used to check errors returned from the Authentication API and handle them as necessary, for example
tokens, err := auth.OAuth.LoginWithPassword(context.Background(), oauth.LoginWithPasswordRequest{ Username: "test@example.com", Password: "hunter2", }, oauth.IDTokenValidationOptions{}) if err != nil { if aerr, ok := err.(*authentication.Error); ok { if aerr.Err == "mfa_required" { // Handle prompting for MFA usage } } }
Index ¶
- type Authentication
- func (a *Authentication) Do(req *http.Request) (*http.Response, error)
- func (a *Authentication) NewFormRequest(ctx context.Context, method, uri string, payload url.Values, ...) (*http.Request, error)
- func (a *Authentication) NewRequest(ctx context.Context, method, uri string, payload interface{}, ...) (*http.Request, error)
- func (a *Authentication) Request(ctx context.Context, method, uri string, payload interface{}, resp interface{}, ...) error
- func (a *Authentication) URI(path ...string) string
- func (a *Authentication) UserInfo(ctx context.Context, accessToken string, opts ...RequestOption) (user *UserInfoResponse, err error)
- type Database
- type Error
- type MFA
- func (m *MFA) AddAuthenticator(ctx context.Context, accessOrMfaToken string, body mfa.AddAuthenticatorRequest, ...) (a *mfa.AddAuthenticatorResponse, err error)
- func (m *MFA) Challenge(ctx context.Context, body mfa.ChallengeRequest, opts ...RequestOption) (c *mfa.ChallengeResponse, err error)
- func (m *MFA) DeleteAuthenticator(ctx context.Context, accessToken string, authenticatorID string, ...) (err error)
- func (m *MFA) ListAuthenticators(ctx context.Context, accessOrMfaToken string, opts ...RequestOption) (a []mfa.ListAuthenticatorsResponse, err error)
- func (m *MFA) VerifyWithOOB(ctx context.Context, body mfa.VerifyWithOOBRequest, opts ...RequestOption) (t *oauth.TokenSet, err error)
- func (m *MFA) VerifyWithOTP(ctx context.Context, body mfa.VerifyWithOTPRequest, opts ...RequestOption) (t *oauth.TokenSet, err error)
- func (m *MFA) VerifyWithRecoveryCode(ctx context.Context, body mfa.VerifyWithRecoveryCodeRequest, ...) (t *mfa.VerifyWithRecoveryCodeResponse, err error)
- type OAuth
- func (o *OAuth) LoginWithAuthCode(ctx context.Context, body oauth.LoginWithAuthCodeRequest, ...) (t *oauth.TokenSet, err error)
- func (o *OAuth) LoginWithAuthCodeWithPKCE(ctx context.Context, body oauth.LoginWithAuthCodeWithPKCERequest, ...) (t *oauth.TokenSet, err error)
- func (o *OAuth) LoginWithClientCredentials(ctx context.Context, body oauth.LoginWithClientCredentialsRequest, ...) (t *oauth.TokenSet, err error)
- func (o *OAuth) LoginWithGrant(ctx context.Context, grantType string, body url.Values, ...) (t *oauth.TokenSet, err error)
- func (o *OAuth) LoginWithPassword(ctx context.Context, body oauth.LoginWithPasswordRequest, ...) (t *oauth.TokenSet, err error)
- func (o *OAuth) PushedAuthorization(ctx context.Context, body oauth.PushedAuthorizationRequest, ...) (p *oauth.PushedAuthorizationRequestResponse, err error)
- func (o *OAuth) RefreshToken(ctx context.Context, body oauth.RefreshTokenRequest, ...) (t *oauth.TokenSet, err error)
- func (o *OAuth) RevokeRefreshToken(ctx context.Context, body oauth.RevokeRefreshTokenRequest, ...) error
- type Option
- func WithAuth0ClientEnvEntry(key string, value string) Option
- func WithClient(client *http.Client) Option
- func WithClientAssertion(signingKey string, signingAlg string) Option
- func WithClientID(clientID string) Option
- func WithClientSecret(clientSecret string) Option
- func WithIDTokenClockTolerance(clockTolerance time.Duration) Option
- func WithIDTokenSigningAlg(alg string) Option
- func WithNoAuth0ClientInfo() Option
- func WithNoRetries() Option
- func WithRetries(maxRetries int, statuses []int) Option
- type Passwordless
- func (p *Passwordless) LoginWithEmail(ctx context.Context, params passwordless.LoginWithEmailRequest, ...) (t *oauth.TokenSet, err error)
- func (p *Passwordless) LoginWithSMS(ctx context.Context, params passwordless.LoginWithSMSRequest, ...) (t *oauth.TokenSet, err error)
- func (p *Passwordless) SendEmail(ctx context.Context, params passwordless.SendEmailRequest, ...) (r *passwordless.SendEmailResponse, err error)
- func (p *Passwordless) SendSMS(ctx context.Context, params passwordless.SendSMSRequest, opts ...RequestOption) (r *passwordless.SendSMSResponse, err error)
- type RequestOption
- type UserAddress
- type UserInfoResponse
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Authentication ¶
type Authentication struct { Database *Database MFA *MFA OAuth *OAuth Passwordless *Passwordless // contains filtered or unexported fields }
Authentication is the auth client.
func (*Authentication) Do ¶
Do triggers an HTTP request and returns an HTTP response, handling any context cancellations or timeouts.
func (*Authentication) NewFormRequest ¶
func (a *Authentication) NewFormRequest( ctx context.Context, method, uri string, payload url.Values, opts ...RequestOption, ) (*http.Request, error)
NewFormRequest returns a new HTTP request. If the payload is not nil it will be encoded as JSON.
func (*Authentication) NewRequest ¶
func (a *Authentication) NewRequest( ctx context.Context, method, uri string, payload interface{}, opts ...RequestOption, ) (*http.Request, error)
NewRequest returns a new HTTP request. If the payload is not nil it will be encoded as JSON.
func (*Authentication) Request ¶
func (a *Authentication) Request(ctx context.Context, method, uri string, payload interface{}, resp interface{}, opts ...RequestOption) error
Request combines NewRequest and Do, while also handling decoding of response payload. If payload is of type url.Values then a request with content type `application/x-www-form-urlencoded` will be performed otherwise a a request of type `"application/json` will be performed.
func (*Authentication) URI ¶
func (a *Authentication) URI(path ...string) string
URI returns the absolute URL of the Authentication API with any path segments appended to the end.
func (*Authentication) UserInfo ¶
func (a *Authentication) UserInfo(ctx context.Context, accessToken string, opts ...RequestOption) (user *UserInfoResponse, err error)
UserInfo returns a user's profile using the access token obtained during login.
This endpoint will work only if `openid` was granted as a scope for the access token. The user profile information included in the response depends on the scopes requested. For example, a scope of just openid may return less information than a a scope of `openid profile email`.
See: https://auth0.com/docs/api/authentication?http#get-user-info
type Database ¶
type Database manager
Database manager.
func (*Database) ChangePassword ¶
func (d *Database) ChangePassword(ctx context.Context, params database.ChangePasswordRequest, opts ...RequestOption) (string, error)
ChangePassword given a user's email address and a connection, Auth0 will send a change password email.
This endpoint only works for database connections. See: https://auth0.com/docs/api/authentication?http#change-password
func (*Database) Signup ¶
func (d *Database) Signup(ctx context.Context, params database.SignupRequest, opts ...RequestOption) (r *database.SignupResponse, err error)
Signup given a user's credentials and a connection, will create a new user using active authentication.
This endpoint only works for database connections. See: https://auth0.com/docs/api/authentication?http#signup
type Error ¶ added in v1.4.0
type Error struct { StatusCode int `json:"statusCode"` Err string `json:"error"` Message string `json:"error_description"` MFAToken string `json:"mfa_token,omitempty"` }
Error represents errors returned from the Authentication API. The `Err` property can be used to check the error code returned from the API.
func (*Error) GetMFAToken ¶ added in v1.11.0
GetMFAToken returns the MFA token associated with the error, if any.
func (*Error) UnmarshalJSON ¶ added in v1.4.0
UnmarshalJSON implements the json.Unmarshaler interface.
It is required to handle the differences between error responses between the APIs.
type MFA ¶ added in v1.4.0
type MFA manager
MFA exposes requesting an MFA challenge and verifying MFA methods.
func (*MFA) AddAuthenticator ¶ added in v1.11.0
func (m *MFA) AddAuthenticator(ctx context.Context, accessOrMfaToken string, body mfa.AddAuthenticatorRequest, opts ...RequestOption) (a *mfa.AddAuthenticatorResponse, err error)
AddAuthenticator Associates or adds a new authenticator for multi-factor authentication (MFA).
See: https://auth0.com/docs/api/authentication#add-an-authenticator
func (*MFA) Challenge ¶ added in v1.4.0
func (m *MFA) Challenge(ctx context.Context, body mfa.ChallengeRequest, opts ...RequestOption) (c *mfa.ChallengeResponse, err error)
Challenge requests a challenge for multi-factor authentication (MFA) based on the challenge types supported by the application and user.
See: https://auth0.com/docs/api/authentication#challenge-request
func (*MFA) DeleteAuthenticator ¶ added in v1.11.0
func (m *MFA) DeleteAuthenticator(ctx context.Context, accessToken string, authenticatorID string, opts ...RequestOption) (err error)
DeleteAuthenticator Deletes an associated authenticator using its ID.
See: https://auth0.com/docs/api/authentication#delete-an-authenticator
func (*MFA) ListAuthenticators ¶ added in v1.11.0
func (m *MFA) ListAuthenticators(ctx context.Context, accessOrMfaToken string, opts ...RequestOption) (a []mfa.ListAuthenticatorsResponse, err error)
ListAuthenticators Returns a list of authenticators associated with your application.
See: https://auth0.com/docs/api/authentication#list-authenticators
func (*MFA) VerifyWithOOB ¶ added in v1.4.0
func (m *MFA) VerifyWithOOB(ctx context.Context, body mfa.VerifyWithOOBRequest, opts ...RequestOption) (t *oauth.TokenSet, err error)
VerifyWithOOB verifies an MFA challenge using an out-of-band challenge (OOB), either push notification, SMS, or voice.
See: https://auth0.com/docs/api/authentication#verify-with-out-of-band-oob-
func (*MFA) VerifyWithOTP ¶ added in v1.4.0
func (m *MFA) VerifyWithOTP(ctx context.Context, body mfa.VerifyWithOTPRequest, opts ...RequestOption) (t *oauth.TokenSet, err error)
VerifyWithOTP verifies an MFA challenge using a one-time password (OTP).
See: https://auth0.com/docs/api/authentication#verify-with-one-time-password-otp-
func (*MFA) VerifyWithRecoveryCode ¶ added in v1.4.0
func (m *MFA) VerifyWithRecoveryCode(ctx context.Context, body mfa.VerifyWithRecoveryCodeRequest, opts ...RequestOption) (t *mfa.VerifyWithRecoveryCodeResponse, err error)
VerifyWithRecoveryCode verifies an MFA challenge using a recovery code.
See: https://auth0.com/docs/api/authentication#verify-with-recovery-code
type OAuth ¶
type OAuth manager
OAuth exposes logging in using OAuth based APIs.
func (*OAuth) LoginWithAuthCode ¶
func (o *OAuth) LoginWithAuthCode(ctx context.Context, body oauth.LoginWithAuthCodeRequest, validationOptions oauth.IDTokenValidationOptions, opts ...RequestOption) (t *oauth.TokenSet, err error)
LoginWithAuthCode performs the Authorization Code grant type OAuth 2.0 grant.
This is the flow that regular web apps use to access an API. Use this endpoint to exchange an Authorization Code for a token.
See: https://auth0.com/docs/api/authentication?http#authorization-code-flow44
func (*OAuth) LoginWithAuthCodeWithPKCE ¶
func (o *OAuth) LoginWithAuthCodeWithPKCE(ctx context.Context, body oauth.LoginWithAuthCodeWithPKCERequest, validationOptions oauth.IDTokenValidationOptions, opts ...RequestOption) (t *oauth.TokenSet, err error)
LoginWithAuthCodeWithPKCE performs the Authorization Code with Proof Key for Code Exchange OAuth 2.0 grant type.
This flow was originally designed to protect the authorization code flow in mobile apps but its ability to prevent authorization code injection makes it useful for every type of OAuth client, even web apps that use client authentication.
See: https://auth0.com/docs/api/authentication?http#authorization-code-flow-with-pkce45
func (*OAuth) LoginWithClientCredentials ¶
func (o *OAuth) LoginWithClientCredentials(ctx context.Context, body oauth.LoginWithClientCredentialsRequest, validationOptions oauth.IDTokenValidationOptions, opts ...RequestOption) (t *oauth.TokenSet, err error)
LoginWithClientCredentials performs the Client Credentials OAuth 2.0 grant type.
Use this endpoint to directly request an access token by using the Client's credentials (a Client ID and a Client Secret).
See: https://auth0.com/docs/api/authentication?http#client-credentials-flow
func (*OAuth) LoginWithGrant ¶
func (o *OAuth) LoginWithGrant(ctx context.Context, grantType string, body url.Values, validationOptions oauth.IDTokenValidationOptions, opts ...RequestOption) (t *oauth.TokenSet, err error)
LoginWithGrant allows logging in with an OAuth 2.0 grant. This should only be needed if a grant type is not supported byt this SDK.
func (*OAuth) LoginWithPassword ¶
func (o *OAuth) LoginWithPassword(ctx context.Context, body oauth.LoginWithPasswordRequest, validationOptions oauth.IDTokenValidationOptions, opts ...RequestOption) (t *oauth.TokenSet, err error)
LoginWithPassword performs the Password OAuth 2.0 grant that highly-trusted apps use to access an API. In this flow, the end-user is asked to fill in credentials (username/password), typically using an interactive form in the user-agent (browser). This information is sent to the backend and from there to Auth0. It is therefore imperative that the application is absolutely trusted with this information. For single-page applications and native/mobile apps, we recommend using web flows instead.
See: https://auth0.com/docs/api/authentication#resource-owner-password
Use the `Header` RequestOption to set the `auth0-forwarded-for` header to an end-user's IP if you you want brute force protection to work in server-side scenarios. See https://auth0.com/docs/get-started/authentication-and-authorization-flow/avoid-common-issues-with-resource-owner-password-flow-and-attack-protection
func (*OAuth) PushedAuthorization ¶ added in v1.4.0
func (o *OAuth) PushedAuthorization(ctx context.Context, body oauth.PushedAuthorizationRequest, opts ...RequestOption) (p *oauth.PushedAuthorizationRequestResponse, err error)
PushedAuthorization performs a Pushed Authorization Request that can be used to initiate an OAuth flow from the backchannel instead of building a URL.
func (*OAuth) RefreshToken ¶
func (o *OAuth) RefreshToken(ctx context.Context, body oauth.RefreshTokenRequest, validationOptions oauth.IDTokenValidationOptions, opts ...RequestOption) (t *oauth.TokenSet, err error)
RefreshToken is used to refresh and access token using the refresh token you got during authorization.
See: https://auth0.com/docs/api/authentication?http#refresh-token
func (*OAuth) RevokeRefreshToken ¶
func (o *OAuth) RevokeRefreshToken(ctx context.Context, body oauth.RevokeRefreshTokenRequest, opts ...RequestOption) error
RevokeRefreshToken is used to invalidate a refresh token if it has been compromised.
The behaviour of this endpoint depends on the state of the **Refresh Token Revocation Deletes Grant** toggle. If this toggle is enabled, then each revocation request invalidates not only the specific token, but all other tokens based on the same authorization grant. This means that all refresh tokens that have been issued for the same user, application, and audience will be revoked. If this toggle is disabled, then only the refresh token is revoked, while the grant is left intact.
See: https://auth0.com/docs/api/authentication?http#revoke-refresh-token
type Option ¶
type Option func(*Authentication)
Option is used for passing options to the Authentication client.
func WithAuth0ClientEnvEntry ¶
WithAuth0ClientEnvEntry allows adding extra environment keys to the client information.
func WithClient ¶
WithClient configures to use the provided client for authentication and JWKS calls.
func WithClientAssertion ¶ added in v1.0.1
WithClientAssertion configures the signing key to be used when performing Private Key JWT Auth.
func WithClientID ¶
WithClientID configures the Client ID to be provided with requests if one is not provided.
func WithClientSecret ¶
WithClientSecret configures the Client Secret to be provided with requests if one is not provided.
func WithIDTokenClockTolerance ¶
WithIDTokenClockTolerance configures the allowed clock tolerance when validating time based claims.
func WithIDTokenSigningAlg ¶
WithIDTokenSigningAlg configures the signing algorithm used for the ID token.
func WithNoAuth0ClientInfo ¶
func WithNoAuth0ClientInfo() Option
WithNoAuth0ClientInfo configures the management client to not send the "Auth0-Client" header at all.
func WithNoRetries ¶
func WithNoRetries() Option
WithNoRetries configures the management client to only retry under the conditions provided.
func WithRetries ¶
WithRetries configures the management client to only retry under the conditions provided.
type Passwordless ¶
type Passwordless manager
Passwordless exposes logging in using the passwordless APIs.
func (*Passwordless) LoginWithEmail ¶
func (p *Passwordless) LoginWithEmail(ctx context.Context, params passwordless.LoginWithEmailRequest, validationOptions oauth.IDTokenValidationOptions, opts ...RequestOption) (t *oauth.TokenSet, err error)
LoginWithEmail completes the passwordless flow started in `SendEmail` by exchanging the code for a token.
See: https://auth0.com/docs/api/authentication?http#authenticate-user
func (*Passwordless) LoginWithSMS ¶
func (p *Passwordless) LoginWithSMS(ctx context.Context, params passwordless.LoginWithSMSRequest, validationOptions oauth.IDTokenValidationOptions, opts ...RequestOption) (t *oauth.TokenSet, err error)
LoginWithSMS completes the passwordless flow started in `SendSMS` by exchanging the code for a token.
See: https://auth0.com/docs/api/authentication?http#authenticate-user
func (*Passwordless) SendEmail ¶
func (p *Passwordless) SendEmail(ctx context.Context, params passwordless.SendEmailRequest, opts ...RequestOption) (r *passwordless.SendEmailResponse, err error)
SendEmail starts a passwordless flow by sending a link or code via email.
In order to set the `x-request-language` header when sending this request, use the `Header` RequestOption helper.
See: https://auth0.com/docs/api/authentication?http#get-code-or-link
func (*Passwordless) SendSMS ¶
func (p *Passwordless) SendSMS(ctx context.Context, params passwordless.SendSMSRequest, opts ...RequestOption) (r *passwordless.SendSMSResponse, err error)
SendSMS starts a passwordless flow by sending a code via SMS.
In order to set the `x-request-language` header when sending this request, use the `Header` RequestOption helper.
See: https://auth0.com/docs/api/authentication?http#get-code-or-link
type RequestOption ¶
type RequestOption interface {
// contains filtered or unexported methods
}
RequestOption configures a call to Auth0 with query parameters.
func Header ¶
func Header(key, value string) RequestOption
Header configures a request to add HTTP headers to requests made to Auth0.
type UserAddress ¶
type UserAddress struct { // Country component of the address. Country string `json:"country,omitempty"` // Full mailing address, formatted for display or use on a mailing label. Formatted string `json:"formatted,omitempty"` // City or locality component of the address. Locality string `json:"locality,omitempty"` // Zip or postal code component of the address. PostalCode string `json:"postal_code,omitempty"` // State, province, prefecture, or region component of the address. Region string `json:"region,omitempty"` // Full street address component, which may include house number, street name, Post Office Box, // and multi-line extended street address information. StreetAddress string `json:"street_address,omitempty"` }
UserAddress defines a user's address.
type UserInfoResponse ¶
type UserInfoResponse struct { // Unknown claims in the response object that are not defined in this struct will be stored here. AdditionalClaims map[string]interface{} `json:"-"` // The user's preferred postal address. Address *UserAddress `json:"address,omitempty"` // The user's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. Birthdate string `json:"birthdate,omitempty"` // The user's preferred email address. Email string `json:"email,omitempty"` // Whether the user's email address has been verified or not. EmailVerified bool `json:"email_verified,omitempty"` // Surname(s) or last name(s) of the user. FamilyName string `json:"family_name,omitempty"` // The user's gender. Gender string `json:"gender,omitempty"` // Given name(s) or first name(s) of the user. GivenName string `json:"given_name,omitempty"` // The user's locale, represented as a BCP47 language tag. Locale string `json:"locale,omitempty"` // Middle name(s) of the user. MiddleName string `json:"middle_name,omitempty"` // Full name of the user in displayable form including all name parts, possibly including titles and // suffixes, ordered according to the user's locale and preferences. Name string `json:"name,omitempty"` // Casual name of the user that may or may not be the same as FirstName. Nickname string `json:"nickname,omitempty"` // The user's preferred telephone number. PhoneNumber string `json:"phone_number,omitempty"` // Whether the user's phone number has been verified or not. PhoneNumberVerified bool `json:"phone_number_verified,omitempty"` // URL of the user's profile picture. Picture string `json:"picture,omitempty"` // Shorthand name by which the user wishes to be referred by, such as janedoe or j.doe. PreferredUsername string `json:"preferred_username,omitempty"` // URL of the user's profile page. Profile string `json:"profile,omitempty"` // The Auth0 user identifier. This is unique to each user. Sub string `json:"sub,omitempty"` // Time and date the user's information was last updated. UpdatedAt *time.Time `json:"updated_at"` // URL of the user's web page or blog. Website string `json:"website,omitempty"` // User's time zone as a "tz database name". ZoneInformation string `json:"zoneinfo,omitempty"` }
UserInfoResponse defines the response from the user info API.
func (*UserInfoResponse) UnmarshalJSON ¶
func (u *UserInfoResponse) UnmarshalJSON(b []byte) error
UnmarshalJSON implements the json.Unmarshaler interface.
It is required to handle the mapping of unknown claims from the main response body into the `AdditionalClaims` field on the struct.