I want to login auth0 using Usename/Password for getting AccessToken. Prev: Note
Methods
GetAccessToken
package utils
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"
)
type TokenResponse struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
Scope string `json:"scope"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
}
func GetAccessToken(t *testing.T) string {
connection := "Username-Password-Authentication"
grantType := "password"
scope := "openid+name+email+nickname"
url := "https://<tenant name>.auth0.com/oauth/token"
payload := strings.NewReader(
fmt.Sprintf(
"client_id=%s&username=%s&password=%s&grant_type=%s&scope=%s&connection=%s",
ClientId, E2eEmail, E2ePassword, grantType, scope, connection,
))
req, err := http.NewRequest("POST", url, payload)
if err != nil {
t.Fatal(err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
var tokenResponse TokenResponse
if err := json.Unmarshal(body, &tokenResponse); err != nil {
t.Fatal(err)
}
return tokenResponse.AccessToken
}
and
E2eEmail = "e2e-test@example.com"
E2ePassword = "PassW0rd"
ClientId = "<clientId of application>"
Get UserInfo
type Auth0User struct {
Sub string `json:"sub"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Nickname string `json:"nickname"`
Name string `json:"name"`
Picture string `json:"picture"`
Locale string `json:"locale"`
UpdatedAt string `json:"updated_at"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
}
func GetUserInfo(ctx context.Context, accessToken string) (Auth0User, error) {
url := fmt.Sprintf("https://%s/userinfo", Auth0Url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
logger.WithContext(ctx).Error("failed to create request err",
zap.String("endpoint", url),
zap.Error(err))
return nil, err
}
req.Header.Add("Authorization", "Bearer "+accessToken)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
logger.WithContext(ctx).Error("auth0 returns err",
zap.String("endpoint", url),
zap.Error(err))
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.WithContext(ctx).Error("Error reading response body: ",
zap.String("endpoint", url),
zap.Error(err))
return nil, err
}
var auth0user Auth0User
err = json.Unmarshal([]byte(body), &auth0user)
if err != nil {
logger.WithContext(ctx).Error(
"Unmarshal failed",
zap.String("body", body),
zap.Error(err),
)
return nil, err
}
return auth0user, nil
}
and
Auth0Url = "<tenant name>.auth0.com"