Giter VIP home page Giter VIP logo

auth0's Introduction

THIS REPOSITORY HAS MOVED

This repository has moved into the Auth0 organization where it will be maintained at github.com/auth0/go-auth0.

Auth0 Go SDK

Go Reference Build Maintainability Test Coverage

Documentation

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

Management API

The Auth0 Management API is meant to be used by back-end servers or trusted parties performing administrative tasks. Generally speaking, anything that can be done through the Auth0 dashboard (and more) can also be done through this API.

Usage

import (
	"gopkg.in/auth0.v5"
	"gopkg.in/auth0.v5/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:

Tests

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

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.

Create a free Auth0 Account

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

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.

Author

Alex Kalyvitis

License

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

auth0's People

Contributors

alexkappa avatar apamildner avatar apricote avatar bishtawi avatar cyx avatar epintos avatar gagalago avatar hypnoglow avatar jayhelton avatar jmaeso avatar ken-molnar-solera avatar kgunbin avatar kpurdon avatar lambdalisue avatar mattoddie avatar mcalster avatar mlafeldt avatar nishanths avatar ollystephens avatar relu avatar rene00 avatar sergiught avatar sethyates avatar shushen avatar simonbarendse avatar toshitanian avatar twistedstream avatar widcket avatar yinzara avatar yvovandoorn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth0's Issues

User model does not have "picture" field

Auth0 API returns the url to the profile picture of a user as part of the fields retured for a user.

The management.User model however does not have the picture field and therefore not extracting this value from the response.

Fail to read user details for a given Github's user_id

What happened:

I get the following error when I try to read user details for a given Github's user_id:

cannot unmarshal number into Go struct field UserIdentity.identities.user_id of type string.

Steps to reproduce

api, err := management.New(auth0Issuer, auth0ClientID, auth0ClientSecret)
if err != nil {
     ...
}
u, err := api.User.Read(githubUserID)

GET /api/v2/users/{github_user_id} returns JSON-encoded data.
identities.user_id is a JSON number value and has a string target type.

Migrate repo to go-auth0/auth0

I am considering moving this repo under go-auth0/auth0.

This would make using it via gopkg.in easy and we can release new versions more confidently.

Importing would be something like:

import gopkg.in/auth0.v1

Passwordless Connection cannot be changed to use MessagingServiceSid

The Options for Passwordless Sms determine if Passwordless uses a single Twilio "From" phone number or a "MessagingServiceSid" (which allows you to send from a group of numbers).

When you use the API, you'll see that when you change the UI to select the Radio button to change between the two options, the "from" and "messaging_service_sid" get set to null for whichever one is not selected. If you set a "messaging_service_sid" without setting "from" to null, it will keep the radio button selected on "From" and simply error if the connection is used if no From number is configured (even though a "messaging_service_sid" is properly configured).

Currently the "From" field of "ConnectionOptionsSms" is set to "omitempty" which prevents null from ever being sent.

I will be submitting a PR that removes this option and some updated tests to verify. "MessagingServiceSid" already did not have "omitempty" so no change was required.

Here is an example response from GET /connection for the SMS connection with a messaging_service_sid set:

{
    "id": "con_XXXXXXXXXX",
    "options": {
      "from": null,
      "name": "sms",
      "totp": {
        "length": 6,
        "time_step": 200
      },
      "syntax": "liquid",
      "template": "Your one-time secure access code is: {{ password }}\n",
      "authParams": {
        "scope": "openid profile read:campaign read:drawing read:offer read:reward read:template read:message create:message",
        "connection": "sms"
      },
      "twilio_sid": "XXXXXXXX",
      "twilio_token": "XXXXXXXXX",
      "disable_signup": true,
      "messaging_service_sid": "XXXXXXXXXXX",
      "brute_force_protection": true
    },
    "strategy": "sms",
    "name": "sms",
    "is_domain_connection": false,
    "realms": [
      "sms"
    ],
    "enabled_clients": [
      "XXXXXXXXXX"
    ]
  }

And here is one with the "from" set:

{
    "id": "XXXXXXXX",
    "options": {
      "from": "+15555555555",
      "name": "sms",
      "totp": {
        "length": 6,
        "time_step": 200
      },
      "syntax": "liquid",
      "template": "Your one-time secure access code is: {{ password }}\n",
      "authParams": {
        "scope": "openid profile read:campaign read:drawing read:offer read:reward read:template read:message create:message",
        "connection": "sms"
      },
      "twilio_sid": "XXXXXXXX",
      "twilio_token": "XXXXXXXXXX",
      "disable_signup": true,
      "messaging_service_sid": null,
      "brute_force_protection": true
    },
    "strategy": "sms",
    "name": "sms",
    "is_domain_connection": false,
    "realms": [
      "sms"
    ],
    "enabled_clients": [
      "XXXXXXXXXXX"
    ]
  }

Unable to find ClientId of created client

The API signature to create a client is as follows:

func (cm *ClientManager) Create(c *Client) (err error)

If a user sets c.ClientID to a desirable value, you get a 403 Forbidden with a message: This operation must be authorized by Auth0.

If a user doesn't set c.ClientID, the request succeeds but then there's no way to retrieve the new ClientID because the method call just returns nil.

A quick look suggests all POST requests have the same issue? Is there willingness to change this behavior, it would be a big breaking change, but pretty much renders this SDK useless to me

Cannot PATCH a User because of required connection field

Use case:

mgmt, err := management.New(domain, clientID, clientSecret)
if err != nil {
	panic(err)
}

err = mgmt.User.Update(userID, &management.User{
	AppMetadata: map[string]interface{}{
		"a": "b",
	},
})
if err != nil {
	log.Fatal(err)
}
}

It results in the error:

2018/08/27 22:15:55 400 Bad Request: Payload validation error: 'String is too short (0 chars), minimum 1' on property connection (The connection name. This field is not itself updateable but is needed when updating email, email_verified, username or password).

connection property should not be required when updating fields like app_metadata.

Failures when using IncludeTotals(true)

When using the IncludeTotals request option with something like the Users endpoint, a json unmarshal error occurs because the response body shape changes from an array of users to an object containing a field with the array of users.

users, err := a.m.User.Search(
	management.IncludeTotals(true),
	management.Parameter("sort", "email:1"),
)
// err is "json: cannot unmarshal object into Go value of type []*management.User"

Before I start submitting PRs I wanted to validate that this is something you are interested in taking in.

Support page_background gradient for Branding

Endpoint: https://auth0.com/docs/api/management/v2#!/Branding/patch_branding

Currently only the string syntax for colors.page_background is supported. It would be great, if you could also support the Color Gradient object syntax.

Currently supported syntax:

{
  "colors": {
    "page_background": "#f9f9f9", // <- Only hex string
    "primary": "#e74c3c"
  },
  "favicon_url": "https://example.com/favicon.ico",
  "logo_url": "https://example.com/logo.png"
}

Color Gradient Syntax:

{
  "colors": {
    "page_background": { // Full object to describe color gradient
      "type": "linear-gradient",
      "start": "#f3c2bd",
      "end": "#e74c3c",
      "angle_deg": 35
    },
    "primary": "#e74c3c"
  },
  "favicon_url": "https://example.com/favicon.ico",
  "logo_url": "https://example.com/logo.png"
}

Empty lists arnt being serialized in the JSON sent to auth0

All of the structs in this codebase uses pointers instead of primitives. I assume this was because the JSON option omitempty would omit empty values (false, 0, empty string) from being serialized, preventing the library from being able to sending empty values to Auth0.

The one exception to the all pointer convention is lists. Lists in the structs are actual lists, []interface{}, instead of pointer to lists, *[]interface{}. This makes it impossible to send an empty list to auth0.

I dont know the full impact on changing all lists to be pointer to lists, or updating all lists to remove the omitempty tag, but something has got to give as currently its impossible to send an empty list.

Handle token expiration

Currently, there is a StaticTokenSource created that would never refresh the token. This is ok for terraform-provider-auth0 and similar apps with short-lived sessions.

However, this library cannot be used in long-running applications, like an http server. Once token expires, all requests would fail, and a new Management instance have to be created.

Possible solution: replace StaticTokenSource with token source implementing token renewal. I'm not sure if this works out-of-the-box for client_credentials grant. Also, there is a https://godoc.org/golang.org/x/oauth2/clientcredentials package that might provide an easy solution for this.


If you approve the idea, I can dig into it to see if I can provide a solution and submit a PR.

Change Tenant SessionLifetime and IdleSessionLifetime to float64

Change data type of Tenant SessionLifetime and IdleSessionLifetime to float64.

It seems that the Auth0 API allows saving fractions of an hour in these fields causing the marshaling/unmarshaling to fail when such values are presented.

type Tenant struct {
 
        // Login session lifetime, how long the session will stay valid (unit:
        // hours).
-       SessionLifetime *int `json:"session_lifetime,omitempty"`
+       SessionLifetime *float64 `json:"session_lifetime,omitempty"`
 
        // Force a user to login after they have been inactive for the specified number (unit: hours)
-       IdleSessionLifetime *int `json:"idle_session_lifetime,omitempty"`
+       IdleSessionLifetime *float64 `json:"idle_session_lifetime,omitempty"`

See: alexkappa/terraform-provider-auth0#233

Make all calls context aware

There is no way to pass a context to calls with the management client, so things like per-call tracing, timeouts, etc. are not possible. It is idiomatic in Go to utilize context.Context for non-trivial code paths such as those performing an RPC request.

DisplayName field missing in Connection struct

The connection struct in management/connection.go doesn't have a field for getting or setting the Display Name for Auth0 connections.

Basically, the change needed is to change this:

type Connection struct {
	// A generated string identifying the connection.
	ID *string `json:"id,omitempty"`

	// The name of the connection. Must start and end with an alphanumeric
	// character and can only contain alphanumeric characters and '-'. Max
	// length 128.
	Name *string `json:"name,omitempty"`
        ...

into this:

type Connection struct {
	// A generated string identifying the connection.
	ID *string `json:"id,omitempty"`

	// The name of the connection. Must start and end with an alphanumeric
	// character and can only contain alphanumeric characters and '-'. Max
	// length 128.
	Name *string `json:"name,omitempty"`
	DisplayName *string `json:"display_name,omitempty"`
        ....

ref:

Name *string `json:"name,omitempty"`

Add Access Token to User Identity model

I need to access the access token when a user logins in with their google account but field is missing.

type UserIdentity struct {
Connection *string json:"connection,omitempty"
UserID *string json:"user_id,omitempty"
Provider *string json:"provider,omitempty"
IsSocial *bool json:"isSocial,omitempty"
}

to

type UserIdentity struct {
Connection *string json:"connection,omitempty"
UserID *string json:"user_id,omitempty"
Provider *string json:"provider,omitempty"
IsSocial *bool json:"isSocial,omitempty"
AccessToken *string json:"access_token,omitempty"

}

Error handling

Hi @alexkappa,

on creation of a user, we'd like to handle different types of returned errors differently. For example, an error for an email address that is already in use would be handled differently than an error for a too weak password.

Example:

err := m.User.Create(user)
if IsErrEmailAlreadyExists(err) {
  // handle
}
if IsErrPasswordTooWeak(err) {
  // handle
}
...

How would you feel about adding these error check functions? Do you have other suggestions?

I'm happy to take a crack at it once we have decided what way to go with this.

Bug when decoding Social Google Connection

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

AllowedAudiences []interface{} `json:"allowed_audiences,omitempty"`

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

Not Possible to Authorize APIs to Application

Hello,

Currently there is way way to add APIs (as they are called in the dashboard, here they are referred to as resource servers) to applications (clients). Is there a plan to make this possible via an API call?

This would be very useful and helpful with automation (for example when trying to use Terraform to manage Auth0 resources).

Currently it can only be done manually by clicking through the dashboard UI which is not ideal.

Timeout issue or missing retry?

Tried to use management client in my handler, but got this error below:

failed to get management client for auth0. error: Post https://pmitc.auth0.com/oauth/token: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

It doesn't seem to be timeout issue to me, as it's not taking over 1 minute to finish the request.

It'd be good that it can provide retry functionality to make it stable.

Listing connections with strategy but without options will return a json error

When listing connections using management.WithFields("strategy") the connection options will fail to unmarshal and a unexpected end of JSON input error will be returned.

Consider:

 _, err := m.Connection.List(management.WithFields("id", "strategy"))
fmt.Println(err)

_, err = m.Connection.List(management.WithFields("id", "strategy", "options"))
fmt.Println(err)

 _, err = m.Connection.List(management.WithFields("id", "name"))
fmt.Println(err)

which prints:

unexpected end of JSON input
<nil>
<nil>

I believe the error happens within UnmarshalJSON:

		err = json.Unmarshal(w.RawOptions, &v)
		if err != nil {
			return err
		}

w.RawOptions will be nil when a returned connection does not contain the options field but does contain a strategy field.

A more verbose reproduction:

% cat main.go
package main

import (
        "encoding/json"
        "fmt"

        "gopkg.in/auth0.v5/management"
)

func main() {
        var data = `{"id":"test","strategy":"auth0","is_domain_connection":false}`
        c := management.Connection{}
        err := json.Unmarshal([]byte(data), &c)
        if err != nil {
                fmt.Printf("err1:%s\n", err)
        }

        data = `{"id":"test","strategy":"auth0","is_domain_connection":false,"options":{"passwordPolicy": "good"}}`
        err = json.Unmarshal([]byte(data), &c)
        if err != nil {
                fmt.Printf("err2:%s\n", err)
        }
}
% go run main.go
err1:unexpected end of JSON input
%

#165 should fix this.

Getting azure's upn attribute

Im trying to create an integration with azure but auth0 notifies that sometime azure wont send to auth0 the user's email upon creation so auth0 will get the user's upn (UserPrincipalName) which is an applicable replacement, that most of the times will hold the email.

Look at the bottom of:
https://auth0.com/docs/connections/azuread-adfs-email-verification?_ga=2.142645749.1771189736.1603610793-286699271.1581410788&_gac=1.220607850.1603614771.Cj0KCQjwxNT8BRD9ARIsAJ8S5xa5ttTL_Lyo15V8RN-VrNUkMGgnA1jIJ50_-5N_2-XwjV8LDe3g8DoaAshuEALw_wcB

I can issue a PR that will add it to User in management/user.go but would like to know if there's a more elegant way of getting that upn attribute when querying a user.

Thank you.

Add the ability to log the Auth0 API calls

When it comes to debugging one's terraform configuration, it would be great to be able to log the API calls that were being made.

Something simple like endpoint called and data passed would be a real help. Right now, I'm getting

* auth0_client.test_client: 400 Bad Request: Payload validation error: 'Too few properties defined (0), minimum 1'.

and it's very hard to understand what I'm missing since I can't see the request

Improve handling of zero values

In certain resources we would like to patch with a value that can be considered a zero value in Go terms. Zero values however will be ignored by the omitempty struct annotation.

This is a fairly well known issue, described in detail here.

The SDKs of popular services such GitHub or Amazon AWS define the attributes of their objects with pointers, even for scalar values such as integers or strings.

This could be made easier with #6 in place, for backwards compatibility's sake.

Cannot clear fields in PATCH request

This is also related to #74.

The resource structs use pointers, which will never be marshalled when set to nil due to the omitempty tag. However sometimes that would be required in a PATCH request if you want to clear a field.

As an example the given_name field on a user with the Patch User request: Auth0 does not accept an empty string, and the correct way to clear this field would be to send null in the JSON payload.

I briefly looked for inspiration how this is solved in other SDKs, and found a similar bug in the GitHub SDK: google/go-github#236 where the suggested solution is to manually create a request.

I guess to do this one could expose the underlying *http.Client with a getter or make the request function public. Then you could construct the payload manually:

payload := struct {
    GivenName *string `json:"given_name"`
}{}

Not sure what the other options would be. I guess one could always replace all pointers with some custom type?

Create requests should return the created object.

The Auth0 create API requests return the object just created on success. This should be returned by the Create functions. Some of the information returned (for example Clients) are essential and having to turn around and do a search for the newly created object is inefficient.

Bug in Oauth2 Connection Support

While the request generated by the current implementation of the Oauth2 connection strategy, the token_endpoint and authorization_endpoint are not used by the Oauth2 Social connection.

The correct names are tokenURL and authorizationURL.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.