The Authentication API client provides methods for user authentication, OAuth flows, password operations, and user information retrieval.
Initializing the Client
Create an authentication client by providing your Auth0 domain and authentication options.
Basic Initialization with Client Credentials
Initialize the authentication client with a client ID and client secret:import (
"context"
"github.com/auth0/go-auth0/v2/authentication"
)
auth, err := authentication.New(
context.Background(),
"your-tenant.auth0.com",
authentication.WithClientID("YOUR_CLIENT_ID"),
authentication.WithClientSecret("YOUR_CLIENT_SECRET"),
)
if err != nil {
log.Fatalf("Error creating authentication client: %v", err)
}
Initialize with Private Key JWT
For enhanced security, use Private Key JWT authentication:auth, err := authentication.New(
context.Background(),
"your-tenant.auth0.com",
authentication.WithClientID("YOUR_CLIENT_ID"),
authentication.WithClientAssertion(privateKeyPEM, "RS256"),
)
Common Authentication Operations
Retrieve user profile information using an access token:
user, err := auth.UserInfo(ctx, accessToken)
if err != nil {
return err
}
fmt.Printf("User: %s (%s)\n", user.Name, user.Email)
fmt.Printf("Email verified: %v\n", user.EmailVerified)
The UserInfoResponse includes standard OIDC claims plus any additional custom claims:
// Access standard OIDC claims
fmt.Println(user.Sub) // User ID
fmt.Println(user.Email) // Email address
fmt.Println(user.EmailVerified) // Email verification status
fmt.Println(user.Name) // Full name
fmt.Println(user.GivenName) // First name
fmt.Println(user.FamilyName) // Last name
fmt.Println(user.Picture) // Profile picture URL
fmt.Println(user.PhoneNumber) // Phone number
Database Connection Operations
The authentication client provides methods for user signup and password management through database connections.
User Signup
Create a new user in a database connection:
import "github.com/auth0/go-auth0/v2/authentication/database"
signupReq := &database.SignupRequest{
ClientID: "YOUR_CLIENT_ID",
Email: "[email protected]",
Password: "SecurePassword123!",
Connection: "Username-Password-Authentication",
Username: "newuser",
GivenName: "John",
FamilyName: "Doe",
UserMetadata: &map[string]interface{}{
"preference": "email",
"plan": "premium",
},
}
signupResp, err := auth.Database.Signup(ctx, signupReq)
if err != nil {
return err
}
fmt.Printf("Created user: %s (ID: %s)\n", signupResp.Email, signupResp.ID)
Password Reset
Initiate a password reset for a user:
changePasswordReq := &database.ChangePasswordRequest{
ClientID: "YOUR_CLIENT_ID",
Email: "[email protected]",
Connection: "Username-Password-Authentication",
}
err := auth.Database.ChangePassword(ctx, changePasswordReq)
if err != nil {
return err
}
fmt.Println("Password reset email sent")
OAuth Operations
The OAuth client provides methods for various OAuth 2.0 flows.
Login with Password Grant
The Password grant should only be used for highly trusted applications. Consider using Authorization Code flow with PKCE for better security.
import "github.com/auth0/go-auth0/v2/authentication/oauth"
loginReq := &oauth.LoginWithPasswordRequest{
ClientAuthentication: oauth.ClientAuthentication{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
},
Username: "[email protected]",
Password: "userpassword",
Scope: "openid profile email",
Audience: "https://your-api.example.com",
}
tokens, err := auth.OAuth.LoginWithPassword(ctx, loginReq)
if err != nil {
return err
}
fmt.Printf("Access Token: %s\n", tokens.AccessToken)
fmt.Printf("Expires In: %d seconds\n", tokens.ExpiresIn)
Exchange Authorization Code
Exchange an authorization code for tokens:
authCodeReq := &oauth.LoginWithAuthCodeRequest{
ClientAuthentication: oauth.ClientAuthentication{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
},
Code: "AUTHORIZATION_CODE",
RedirectURI: "https://myapp.com/callback",
}
tokens, err := auth.OAuth.LoginWithAuthCode(ctx, authCodeReq)
if err != nil {
return err
}
Authorization Code with PKCE
For public clients (mobile/SPA apps), use PKCE:
pkceReq := &oauth.LoginWithAuthCodeWithPKCERequest{
ClientAuthentication: oauth.ClientAuthentication{
ClientID: "YOUR_CLIENT_ID",
},
Code: "AUTHORIZATION_CODE",
CodeVerifier: "CODE_VERIFIER_STRING",
RedirectURI: "https://myapp.com/callback",
}
tokens, err := auth.OAuth.LoginWithAuthCodeWithPKCE(ctx, pkceReq)
Client Credentials Flow
For machine-to-machine authentication:
clientCredsReq := &oauth.LoginWithClientCredentialsRequest{
ClientAuthentication: oauth.ClientAuthentication{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
},
Audience: "https://your-api.example.com",
}
tokens, err := auth.OAuth.LoginWithClientCredentials(ctx, clientCredsReq)
if err != nil {
return err
}
fmt.Printf("Access Token: %s\n", tokens.AccessToken)
Refresh Tokens
Exchange a refresh token for new access tokens:
refreshReq := &oauth.RefreshTokenRequest{
ClientAuthentication: oauth.ClientAuthentication{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
},
RefreshToken: "REFRESH_TOKEN",
Scope: "openid profile email",
}
tokens, err := auth.OAuth.RefreshToken(ctx, refreshReq)
if err != nil {
return err
}
Revoke Refresh Tokens
Revoke a refresh token to prevent further use:
revokeReq := &oauth.RevokeRefreshTokenRequest{
ClientAuthentication: oauth.ClientAuthentication{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
},
Token: "REFRESH_TOKEN_TO_REVOKE",
}
err := auth.OAuth.RevokeRefreshToken(ctx, revokeReq)
if err != nil {
return err
}
Pushed Authorization Requests (PAR)
PAR allows you to push authorization parameters directly to the authorization server:
parReq := &oauth.PushedAuthorizationRequest{
ClientAuthentication: oauth.ClientAuthentication{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
},
RedirectURI: "https://myapp.com/callback",
Scope: "openid profile email",
Audience: "https://your-api.example.com",
ResponseType: "code",
ResponseMode: "query",
Nonce: "random-nonce-value",
CodeChallenge: "BASE64_ENCODED_SHA256_HASH",
}
parResp, err := auth.OAuth.PushedAuthorizationRequest(ctx, parReq)
if err != nil {
return err
}
fmt.Printf("Request URI: %s\n", parResp.RequestURI)
fmt.Printf("Expires In: %d seconds\n", parResp.ExpiresIn)
// Use the request_uri in your authorization request
authorizeURL := fmt.Sprintf(
"https://your-tenant.auth0.com/authorize?client_id=%s&request_uri=%s",
"YOUR_CLIENT_ID",
parResp.RequestURI,
)
ID Token Validation
The authentication client automatically validates ID tokens. For advanced validation:
import "time"
validationOpts := &oauth.IDTokenValidationOptions{
MaxAge: time.Hour * 24,
Nonce: "expected-nonce-value",
Organization: "org_abc123",
}
// Validation happens automatically during token exchange
tokens, err := auth.OAuth.LoginWithAuthCode(ctx, authCodeReq)
if err != nil {
return err
}
// ID token is already validated at this point
fmt.Printf("Validated ID Token: %s\n", tokens.IDToken)
Error Handling
Handle authentication errors appropriately:
tokens, err := auth.OAuth.LoginWithPassword(ctx, loginReq)
if err != nil {
// Check for specific error types
fmt.Printf("Authentication error: %v\n", err)
return err
}
if tokens.AccessToken == "" {
return fmt.Errorf("no access token received")
}
Complete Example
Here’s a complete example demonstrating authentication flows:
package main
import (
"context"
"fmt"
"log"
"github.com/auth0/go-auth0/v2/authentication"
"github.com/auth0/go-auth0/v2/authentication/database"
"github.com/auth0/go-auth0/v2/authentication/oauth"
)
func main() {
// Initialize authentication client
auth, err := authentication.New(
context.Background(),
"your-tenant.auth0.com",
authentication.WithClientID("YOUR_CLIENT_ID"),
authentication.WithClientSecret("YOUR_CLIENT_SECRET"),
)
if err != nil {
log.Fatalf("Error creating authentication client: %v", err)
}
ctx := context.Background()
// Sign up a new user
signupReq := &database.SignupRequest{
Email: "[email protected]",
Password: "SecurePassword123!",
Connection: "Username-Password-Authentication",
GivenName: "John",
FamilyName: "Doe",
}
user, err := auth.Database.Signup(ctx, signupReq)
if err != nil {
log.Fatalf("Error signing up user: %v", err)
}
fmt.Printf("Created user: %s\n", user.Email)
// Exchange credentials for tokens
loginReq := &oauth.LoginWithPasswordRequest{
Username: "[email protected]",
Password: "SecurePassword123!",
Scope: "openid profile email",
}
tokens, err := auth.OAuth.LoginWithPassword(ctx, loginReq)
if err != nil {
log.Fatalf("Error logging in: %v", err)
}
fmt.Printf("Access Token: %s\n", tokens.AccessToken)
// Get user info
userInfo, err := auth.UserInfo(ctx, tokens.AccessToken)
if err != nil {
log.Fatalf("Error getting user info: %v", err)
}
fmt.Printf("User Info: %s (%s)\n", userInfo.Name, userInfo.Email)
}
Next Steps
Management Client
Learn how to use the Management API client
Request Options
Customize requests with headers, retries, and more