Go client library for the Auth0 platform.

Auth0 Go SDK

GoDoc License Release Tests Codecov


Go client library for the Auth0 platform.

Note: This SDK was previously maintained under go-auth0/auth0.


Table of Contents


Installation

go get github.com/auth0/go-auth0

[table of contents]

Documentation

Reference documentation can be found at pkg.go.dev. For more information about Auth0 please visit the Auth0 Docs page and the Auth0 Management API Docs.

[table of contents]

Usage

import (
	"github.com/auth0/go-auth0"
	"github.com/auth0/go-auth0/management"
)

Initialize a new client using a domain, client ID and secret.

m, err := management.New(domain, management.WithClientCredentials(id, secret))
if err != nil {
	// handle err
}

With the management client we can now interact with the Auth0 Management API.

c := &management.Client{
	Name:        auth0.String("Client Name"),
	Description: auth0.String("Long description of client"),
}

err = m.Client.Create(c)
if err != nil {
	// handle err
}

fmt.Printf("Created client %s\n", c.ClientID)

The following Auth0 resources are supported:

[table of contents]

Testing

The tests must run against an Auth0 tenant. They also need an M2M app in that tenant that has been authorized to call the Management API. You can easily set one of these up by creating an API Explorer Application in your tenant.

Then simply create a local .env file with the following settings:

  • AUTH0_DOMAIN: The Domain of the M2M app
  • AUTH0_CLIENT_ID: The Client ID of the M2M app
  • AUTH0_CLIENT_SECRET: The Client Secret of the M2M app
  • AUTH0_DEBUG: Set to true to call the Management API in debug mode, which dumps the HTTP requests and responses to the output

[table of contents]

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when and where users are logging in.
  • Pull data from other sources and add it to the user profile, through JavaScript rules.

[table of contents]

Create a free Auth0 Account

  1. Go to Auth0 and click "Try Auth0 for Free".
  2. Use Google, GitHub or Microsoft Account to login.

[table of contents]

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

[table of contents]

Author

Auth0

[table of contents]

License

This project is licensed under the MIT license. See the LICENSE file for more info.

[table of contents]

Comments
  • Add LastPasswordReset field to management.User struct

    Add LastPasswordReset field to management.User struct

    Describe the problem

    The API provides a last_password_reset field if relevant, but the management.User struct has no field to deserialize it to.

    What was the expected behavior?

    I think it should be possible to read the last_password_reset field when necessary, so this field should be added to the struct.

    Reproduction

    1. Create/sign up as a new user
    2. Set a password
    3. Retrieve this user record from the Auth0 management API
    4. Observe that it is not possible to access the last_password_reset data.

    Environment

    Version v0.10.1

  • feat(management): allows passing a custom token source

    feat(management): allows passing a custom token source

    Description

    This PR adds an API to configure a custom oauth token source. At the moment the APIs provided by the go client do not allow this and force the user to change application settings.

    Testing

    I added a unit test for it

    Checklist

    • [x] I have read and agreed to the terms within the Auth0 Code of Conduct.
    • [x] I have read the Auth0 General Contribution Guidelines.
    • [x] I have reviewed my own code beforehand.
    • [ ] I have added documentation for new/changed functionality in this PR.
    • [ ] All active GitHub checks for tests, formatting, and security are passing.
    • [ ] The correct base branch is being used, if not main.
  • Add profileData key to UserIdentity

    Add profileData key to UserIdentity

    Description

    The key profileData is present in social Identities (see below), but is not in the UserIdentity struct. This means that this SDK cannot be used to retrieve social profile data. Here's an example of the key within an account with two identities:

    ...
      "identities": [
        {
          "connection": "Initial-Connection",
          "user_id": "123xyz",
          "provider": "auth0",
          "isSocial": false
        },
        {
          "connection": "google-oauth2",
          "user_id": "abc123",
          "provider": "google-oauth2",
          "isSocial": true,
          "profileData": {
             "family_name": "some name",
             "picture": "https://cdn.googleusercontent.com/user/abc123"
          }
        }
      ],
    ...
    

    This PR adds a profileData field to UserIdentity with type *map[string]interface{} so arbitrary schemas of social providers can be deserialized.

    References

    This PR was motivated by this thread on the community forum: https://community.auth0.com/t/identity-profiledata-field-not-in-management-api-useridentity/78948

    Testing

    • [x] This change adds test coverage for new/changed/fixed functionality

    Checklist

    • [x] I have read and agreed to the terms within the Auth0 Code of Conduct.
    • [x] I have read the Auth0 General Contribution Guidelines.
    • [x] I have reviewed my own code beforehand.
    • [ ] I have added documentation for new/changed functionality in this PR.
    • [ ] All active GitHub checks for tests, formatting, and security are passing.
    • [x] The correct base branch is being used, if not main.
  • Add Mixpanel log stream

    Add Mixpanel log stream

    🔧 Changes

    • This adds a log stream type and sink for Mixpanel

    🔬 Testing

    • This does not include a recording for tests. I wasn't sure if adding one using my tenant and modifying the URL to use the go-auth0 tenant was appropriate.

    📝 Checklist

    • [x] All new/changed/fixed functionality is covered by tests (or N/A)
    • [ ] I have added documentation for all new/changed functionality (or N/A)

    Please let me know if I missed anything. Happy to add it. Would like this functionality to use with the Terraform provider.

  • Prompt.SetCustomText not passing body

    Prompt.SetCustomText not passing body

    Describe the problem

    I Think i may have discovered a bug - the SetCustomText method does not appear to be passing a body.

    However, I have never written a line of Go before today, so it very possible i have done something wrong.

    Originally discovered by using the terraform provider for setting prompt language texts - and noticing that the body of the request is empty, in auth0 logs.

    Tracked the code backwards the the go sdk, and have produced the following test script.

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"github.com/auth0/go-auth0/management"
    )
    
    func main() {
    	m, err := management.New("CLIENT_DOMAIN", management.WithClientCredentials("CLIENT_ID", "CLIENT_SECRET"))
    	if err != nil {
    		// handle err
    	}
    
    	var body map[string]interface{}
    	err1 := json.Unmarshal([]byte(`{ "login": { "title": "Welcome" } }`), &body)
    	if err1 != nil {
    		fmt.Println(err)
    	}
    
    	err = m.Client.Prompt.SetCustomText("login", "en", body)
    	if err != nil {
    		fmt.Printf("Something broken")
    		fmt.Println(err)
    
    	}
    
    }
    
    

    When i run the code above, I get no output (indicating success) however, the logs in auth0 show no body was passed. (same issue as i encountered with the terraform provider)

    Could someone help to identify if this is an issue, or if i am using this incorrectly?

    What was the expected behavior?

    I expect

    	var body map[string]interface{}
    	err1 := json.Unmarshal([]byte(`{ "login": { "title": "Welcome" } }`), &body)
    	if err1 != nil {
    		fmt.Println(err)
    	}
    
    	err = m.Client.Prompt.SetCustomText("login", "en", body)
    

    To make a PUT request to Auth0 Management API, and the language strings are included in the body of the request when viewing the auth0 logs.

    Reproduction

    Reproduction steps included above :-)

    Environment

    Im not sure how to validate what version of things i am using - i have never written GO before today.

    The go.mod file in my test directory has the following content (this is automatically generated - the only dependency i added with go get was github.com/auth0/go-auth0 :

    module sdk-test
    
    go 1.18
    
    require (
    	github.com/PuerkitoBio/rehttp v1.1.0 // indirect
    	github.com/auth0/go-auth0 v0.6.3 // indirect
    	github.com/golang/protobuf v1.4.2 // indirect
    	golang.org/x/net v0.0.0-20210510120150-4163338589ed // indirect
    	golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
    	google.golang.org/appengine v1.6.6 // indirect
    	google.golang.org/protobuf v1.25.0 // indirect
    )
    

    Any other info i can provide, please let me know.

  • add method to unlink a users identity

    add method to unlink a users identity

    Description

    adds a method to unlink a users identity

    References

    https://auth0.com/docs/api/management/v2#!/Users/delete_user_identity_by_user_id

    Testing

    Checklist

    • [x] I have read and agreed to the terms within the Auth0 Code of Conduct.
    • [x] I have read the Auth0 General Contribution Guidelines.
    • [x] I have reviewed my own code beforehand.
    • [x] I have added documentation for new/changed functionality in this PR.
    • [x] All active GitHub checks for tests, formatting, and security are passing.
    • [x] The correct base branch is being used, if not main.
  • UserIdentity is Missing profileData

    UserIdentity is Missing profileData

    Describe the problem

    The field profileData is present in social User Identities (see below) and retrievable from the REST API, but is not in the UserIdentity struct. This means that this SDK cannot be used to retrieve social profile data. Here's an example of the key within an account with two identities:

    ...
      "identities": [
        {
          "connection": "Initial-Connection",
          "user_id": "123xyz",
          "provider": "auth0",
          "isSocial": false
        },
        {
          "connection": "google-oauth2",
          "user_id": "abc123",
          "provider": "google-oauth2",
          "isSocial": true,
          "profileData": {
             "family_name": "some name",
             "picture": "https://cdn.googleusercontent.com/user/abc123"
          }
        }
      ],
    ...
    

    What was the expected behavior?

    The UserIdentity struct has the profileData field and data.

    Environment

    gopkg.in/auth0.v5 v5.21.1

  • SDK overwrites transport when sending in custom http client with WithClient()

    SDK overwrites transport when sending in custom http client with WithClient()

    Describe the problem

    We want to use our custom HTTP client with the management client. We are using datadog http tracing to trace our http requests, which works by modifying the client's transport to augment it with tracing. However, it seems like our transport/roundtripper is overwritten by the "default" roundtripper in the package and the tracing does not work. When commenting out the WithUserAgent and WithRateLimit in management.New(), we get the desired Transport with tracing.

    What was the expected behavior?

    The calls to auth0 management API should function as normal and traces should appear in DataDog.

    Reproduction

    Here is a repo that replicates a simple version of our setup, that can be used to demonstrate the issue.

    Here are the values that we see for Transport inside our New function when debugging: Before calling management.New()

    Transport = {net/http.RoundTripper | *gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http.roundTripper}
    

    After calling management.New()

    http = {@net/http.Client}
         Transport = {net/http.RoundTripper | *github.com/PuerkitoBio/rehttp.Transport}
    

    Environment

    go-auth0 v0.5.0 Go 1.17

    • Datadog http tracing v1.36.0: https://pkg.go.dev/gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http
  • Sdk itself handles request for Management Api Rate Limiting

    Sdk itself handles request for Management Api Rate Limiting

    From auth0 created by sambhavjain9138: go-auth0/auth0#261

    Question

    we are currently using this SDK to make management api calls. But we face some error due to management api rate limiting. Following is an article for the same. https://auth0.com/docs/troubleshoot/customer-support/operational-policies/rate-limit-policy/management-api-endpoint-rate-limits

    During this request, auth0 returns a status code of 409, which helps us identify that the error is due to rate limiting. So can sdk itself make a small delay and then make a retry, during such responses?

    Even if it doesnt, How can we get this response status code in the response so as to make such check and introduce delay?

  • Every request returns a 401 http response with `Invalid token`

    Every request returns a 401 http response with `Invalid token`

    From auth0 created by Breigner01: go-auth0/auth0#256

    Description

    Package Version

    v5.21.1
    

    Affected Resources

    • management.User

    Sample Code

    type User struct {
    	UserDB    model.User      `json:"user_db"`
    	UserAuth0 management.User `json:"user_auth0"`
    }
    
    func getUserByID(c *gin.Context, db *gorm.DB) {
    	m, err := management.New(os.Getenv("AUTH0_DOMAIN"), management.WithClientCredentials(
    		os.Getenv("AUTH0_CLIENT_ID"),
    		os.Getenv("AUTH0_CLIENT_SECRET"),
    	))
    	if err != nil {
    		panic(err)
    	}
    
    	var usersDB []model.User
    	var users []User
    
    	db.Find(&usersDB)
    
    	for i := range usersDB {
    		auth0User, err := m.User.Read(usersDB[i].UserId)
    		fmt.Println(err)
    		if err != nil {
    			c.JSON(500, gin.H{
    				"message": "Error getting user from Auth0",
    				"error":   err,
    			})
    			return
    		}
    		users = append(users, User{
    			UserDB:    usersDB[i],
    			UserAuth0: *auth0User,
    		})
    	}
    
    	c.JSON(200, gin.H{
    		"user_number": len(users),
    		"users":       users,
    	})
    }
    

    Expected Behavior

    I'm expecting it to return the user asked for.

    Actual Behavior

    I get a 401 http response with the message Unauthorized: Invalid token

    Output

    401 Unauthorized: Invalid token
    

    References

    • #0000

    Community Note

    • Please vote on this issue by adding a 👍 reaction to the original issue to help the community and maintainers prioritize this request
    • Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request
    • If you are interested in working on this issue or have submitted a pull request, please leave a comment
  • Recommended to use interface instead of struct in xxxManager

    Recommended to use interface instead of struct in xxxManager

    From auth0 created by starsz: go-auth0/auth0#226

    Description

    Hello, I found that the xxxManager was defined as a struct. And it was referenced in management.

    https://github.com/go-auth0/auth0/blob/0ed82d242c8bfacb02db3352ef6688591108b371/management/management.go#L85-L106

    https://github.com/go-auth0/auth0/blob/0ed82d242c8bfacb02db3352ef6688591108b371/management/user.go#L280-L282

    Affected Resources

    • management.Xxx
    • management.XxxManager

    Potential Sample Code

    I recommend to use interface instead of struct in xxxManager Like this:

    type UserManager interface{
     Create(u *User, opts ...RequestOption) error
     Read(id string, opts ...RequestOption) (u *User, err error)
     Update(id string, u *User, opts ...RequestOption) (err error) 
     List(opts ...RequestOption) (ul *UserList, err error) 
    ...
    }
    

    So that we can mock the Management.User and do some unit tests.

    The same as other managers.

  • Organizations.List request has bugs with checkpoint paginations params input

    Organizations.List request has bugs with checkpoint paginations params input

    Describe the problem

    While making auth0 call to list all organization, we are getting unexpected results.

    Request:

                     Auth0Client.Organization.List(
    			 management.From(<prev next>),
    		)
    

    When we dont send Take, the Limit is set to 50, but in each request, we dont get a Next value. Start is always set to 0, next to empty string and total to the number of documents.

    When we do send Take (i did set it as 10, then 50), it send start, limit, length, total as 0 and next as a string and with organizations list. First 50 organizations.

    Similar issue: https://github.com/auth0/auth0-python/issues/277

    What was the expected behavior?

    To get next value for list request and proper params for the same with Take value

    Reproduction

    The error is reproducible. Making a call to the following function would help. https://github.com/auth0/go-auth0/blob/main/management/organization.go#L187

    Environment

    • Version of go-auth0 - v0.10.0
  • Organization's OrganizationInvitationList is not behaving as expected

    Organization's OrganizationInvitationList is not behaving as expected

    Describe the problem

    The listing operation for OrganizationInvitation is non-functioning. The API does not provide the total field which breaks the HasNext method.

    What was the expected behavior?

    The OrganizationInvitationList.HasNext should return true when there is actually a next page. The work around is to look at the number of elements returned, if it's equal to the page size, return true. I suspect that this is what auth0's UI is doing.

    Reproduction

    Force pagination to 1 element, create 2 invitations, expect OrganizationInvitationList.HasNext to return true, but it returns false.

    Environment

    version 0.6.0

  • Bug when decoding Social Google Connection

    Bug when decoding Social Google Connection

    From auth0 created by juniocezar: go-auth0/auth0#117

    The allowed audiences field for the Google OAuth2 Social connection has the []interface{} type.

    https://github.com/go-auth0/auth0/blob/1c72b20f2cab2ec7b754b93169a19d773af8d444/management/connection.go#L195

    The Social Google account usually comes enabled by default in Auth0, but if you disable it:

    image

    and run a ConnectionManager.List() to get the list of all connections, this Social Google connection is still being listed.

    {
        "total":1,
        "start":0,
        "limit":50,
        "connections":[
           {
              "id":"con_jBya21zJU4o*****",
              "options":{
                 "email":true,
                 "gmail":false,
                 "orkut":false,
                 "scope":[
                    "email",
                    "profile"
                 ],
                 "sites":false,
                 "tasks":false,
                 "blogger":false,
                 "profile":true,
                 "youtube":false,
                 "calendar":false,
                 "contacts":false,
                 "analytics":false,
                 "client_id":"",
                 "moderator":false,
                 "coordinate":false,
                 "picasa_web":false,
                 "google_plus":false,
                 "google_books":false,
                 "google_drive":false,
                 "spreadsheets":false,
                 "client_secret":"",
                 "document_list":false,
                 "latitude_best":false,
                 "latitude_city":false,
                 "url_shortener":false,
                 "webmaster_tools":false,
                 "chrome_web_store":false,
                 "allowed_audiences":"",
                 "adsense_management":false,
                 "google_drive_files":false,
                 "coordinate_readonly":false,
                 "google_cloud_storage":false,
                 "content_api_for_shopping":false,
                 "google_affiliate_network":false
              },
              "strategy":"google-oauth2",
              "name":"google-oauth2",
              "is_domain_connection":false,
              "realms":[
                 "google-oauth2"
              ],
              "enabled_clients":[
     
              ]
           }
        ]
     }
    

    The problem here is that the allowed_audiences option comes as an empty string, leading to an Unmarshall error.

    json: cannot unmarshal string into Go struct field ConnectionOptionsGoogleOAuth2.allowed_audiences of type []interface {}
    

    I may try to work on a fix for it when I get some spare time

Go client library for the Auth0 platform.

Auth0 Go SDK Go client library for the Auth0 platform. Note: This SDK was previously maintained under go-auth0/auth0. Table of Contents Installation D

Dec 30, 2022
Terraform Provider for the Auth0 platform.

Auth0 Terraform Provider Terraform Provider for the Auth0 platform. Note: This Provider was previously maintained under alexkappa/terraform-provider-a

Dec 21, 2022
auth0 jwt validator with jwks caching

JWT Validator for Auth0 (https://auth0.com/) that caches public JWKS (since there is a limit on calls to public JWKS URL) Example securing a GraphQL s

Mar 4, 2022
Demonstration of sharing secret data between an OAuth/OIDC client and an Identity Providers web client.

OAuth / OIDC Cubbyhole Share secret data between client applications. This is mostly a demonstration of some of the work I've been evaluating at Storj

Mar 21, 2022
A library for performing OAuth Device flow and Web application flow in Go client apps.
A library for performing OAuth Device flow and Web application flow in Go client apps.

oauth A library for Go client applications that need to perform OAuth authorization against a server, typically GitHub.com. Traditionally,

Dec 30, 2022
A library for Go client applications that need to perform OAuth authorization against a server
A library for Go client applications that need to perform OAuth authorization against a server

oauth-0.8.0.zip oauth A library for Go client applications that need to perform OAuth authorization against a server, typically GitHub.com. Traditiona

Oct 13, 2021
Platform-Agnostic Security Tokens implementation in GO (Golang)

Golang implementation of PASETO: Platform-Agnostic Security Tokens This is a 100% compatible pure Go (Golang) implementation of PASETO tokens. PASETO

Jan 2, 2023
Casdoor is a UI-first centralized authentication / Single-Sign-On (SSO) platform based on OAuth 2.0 / OIDC.

A UI-first centralized authentication / Single-Sign-On (SSO) platform based on OAuth 2.0 / OIDC

Dec 29, 2022
ZITADEL - Identity Experience Platform
ZITADEL - Identity Experience Platform

What Is ZITADEL ZITADEL is a "Cloud Native Identity and Access Management" solution built for the cloud era. ZITADEL uses a modern software stack cons

Jan 1, 2023
Generate and verify JWT tokens with Trusted Platform Module (TPM)

golang-jwt for Trusted Platform Module (TPM) This is just an extension for go-jwt i wrote over thanksgiving that allows creating and verifying JWT tok

Oct 7, 2022
manipulate WireGuard with OpenID Connect Client Initiated Backchannel Authentication(CIBA) Flow

oidc-wireguard-vpn manipulate WireGuard with OpenID Connect Client Initiated Backchannel Authentication(CIBA) Flow Requirements Linux WireGuard nftabl

Oct 7, 2022
Golang OpenID Connect Client

adhocore/goic GOIC, Go Open ID Connect, is OpenID connect client library for Golang. It supports the Authorization Code Flow of OpenID Connect specifi

Dec 27, 2022
Go module that allows you to authenticate to Azure with a well known client ID using interactive logon and grab the token

azureimposter Go module that pretends to be any clientID and grabs an authentication token from Azure using interactive login (w/mfa if enabled) and r

Dec 14, 2022
This repository contains a set of tools to help you implement IndieAuth, both server and client, in Go.

This repository contains a set of tools to help you implement IndieAuth, both server and client, in Go.

Nov 26, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Golang
An authorization library that supports access control models like ACL, RBAC, ABAC in Golang

Casbin News: still worry about how to write the correct Casbin policy? Casbin online editor is coming to help! Try it at: https://casbin.org/editor/ C

Jan 2, 2023
Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.

❗ Cache package has been moved to libcache repository Go-Guardian Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to

Dec 23, 2022
JSON Web Token library

About … a JSON Web Token (JWT) library for the Go programming language. Feature complete Full test coverage Dependency free Key management The API enf

Dec 19, 2022
Golang OAuth2 server library

OSIN Golang OAuth2 server library OSIN is an OAuth2 server library for the Go language, as specified at http://tools.ietf.org/html/rfc6749 and http://

Dec 23, 2022
Time-Based One-Time Password (TOTP) and HMAC-Based One-Time Password (HOTP) library for Go.

otpgo HMAC-Based and Time-Based One-Time Password (HOTP and TOTP) library for Go. Implements RFC 4226 and RFC 6238. Contents Supported Operations Read

Dec 19, 2022