hello oryers, the userinfo endpoint is giving me l...
# ory-network
b
hello oryers, the userinfo endpoint is giving me like this its not giving me the user email User Info: {"amr":["password"],"aud": ["f0440b7b-7847-48c0-9305-db95fbbc0536"],"auth_time":1685548408,"iat":1685548591,"iss":"https://xenodochial-ccccve2w.projects.oryapis.com", "rat":1685548579,"sub":"98902064-efbc-4aa8-a61c-992d2f981a4e"} anything am missing here?
Copy code
oAuth2Client := *ory.NewOAuth2Client()
    oAuth2Client.SetClientName(client)
    oAuth2Client.SetClientUri("<http://localhost:3001>")
    oAuth2Client.SetScope("openid")
    oAuth2Client.SetGrantTypes([]string{"authorization_code", "refresh_token", "client_credentials"})
    oAuth2Client.SetResponseTypes([]string{"code", "id_token", "token"})
    oAuth2Client.SetRedirectUris([]string{"<http://localhost:3001/login/generic_oauth>"})
    oAuth2Client.SetTokenEndpointAuthMethod("client_secret_post")
am also using tunnel , ory tunnel --dev --project xenodochial-cxasdasdasdasdasd \ http://localhost:3001
l
You also need the
email
scope for the email to be present on the
id_token
b
you mean like this, oAuth2Client.SetScope("email")
l
When you create the client you’ll want it to be able to use the email scope so
Copy code
oAuth2Client.SetScope("openid email")
and then you’ll want to request those scopes when making the authorization request when the user logs in
b
thank you for the help.
but still having issues,
Copy code
User Info: {"error":"request_unauthorized","error_description":"The request could not be authorized. Check that you provided valid credentials in the right format."}
Copy code
<http://localhost:4000/oauth2/auth?client_id=495d9630-330d-4088-bb81-320620f0dfef&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Flogin%2Fgeneric_oauth&response_type=code&scope=openid+email&state=randomstate>
Copy code
package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"

    ory "<http://github.com/ory/client-go|github.com/ory/client-go>"
    "<http://golang.org/x/oauth2|golang.org/x/oauth2>"
)

var (
    config oauth2.Config
    state  = "randomstate"
    client = "testclient3"
)

// Use this context to access Ory APIs which require an Ory API Key.
var oryAuthedContext = context.WithValue(context.Background(), ory.ContextAccessToken, "ory_pat_tXlKB9RHRQK")

func handleMain(w http.ResponseWriter, r *http.Request) {
    url := config.AuthCodeURL(state)
    fmt.Println("Redirecting user to authorization endpoint:", url)
    http.Redirect(w, r, url, http.StatusFound)
}

func handleCallback(w http.ResponseWriter, r *http.Request) {
    if r.URL.Query().Get("state") != state {
        http.Error(w, "state did not match", http.StatusBadRequest)
        return
    }

    fmt.Println("Received callback from authorization endpoint with state:", r.URL.Query().Get("state"))
    fmt.Println("Exchanging authorization code for access token")

    token, err := config.Exchange(context.Background(), r.URL.Query().Get("code"))
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    fmt.Fprint(w, "Received access token and refresh token")
    fmt.Fprintf(w, "Access Token: %s\n", token.AccessToken)
    fmt.Fprintf(w, "Refresh Token: %s\n", token.RefreshToken)
    fmt.Fprintf(w, "Expiry: %s\n", token.Expiry)

    client := config.Client(context.Background(), token)
    resp, err := client.Get("<http://localhost:4000/userinfo>")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    fmt.Println("Received user information")
    fmt.Fprintf(w, "User Info: %+v\n", string(body))
}

func main() {
    fmt.Println("-------------------")
    fmt.Println("OAuth2 client is being created")
    fmt.Println("-------------------")

    oAuth2Client := *ory.NewOAuth2Client()
    oAuth2Client.SetClientName(client)
    oAuth2Client.SetClientUri("<http://localhost:3001>")
    oAuth2Client.SetScope("openid email offline")
    oAuth2Client.SetGrantTypes([]string{"authorization_code", "refresh_token", "client_credentials"})
    oAuth2Client.SetResponseTypes([]string{"code", "id_token", "token"})
    oAuth2Client.SetRedirectUris([]string{"<http://localhost:3001/login/generic_oauth>"})
    oAuth2Client.SetTokenEndpointAuthMethod("client_secret_post")

    configuration := ory.NewConfiguration()
    configuration.Servers = []ory.ServerConfiguration{
        {
            URL: "<https://xenodochial-e2wects.oryapis.com>",
        },
    }
    clientAPI := ory.NewAPIClient(configuration)
    resp, r, err := clientAPI.OAuth2Api.CreateOAuth2Client(oryAuthedContext).OAuth2Client(oAuth2Client).Execute()
    if err != nil {
        switch r.StatusCode {
        case http.StatusConflict:
            fmt.Fprintf(os.Stderr, "Conflict when creating oAuth2Client: %v\n", err)
        default:
            fmt.Fprintf(os.Stderr, "Error when calling `OAuth2Api.CreateOAuth2Client`: %v\n", err)
            fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
            os.Exit(1)
        }
    }

    fmt.Println("-------------------")
    fmt.Println("OAuth2 client has been created")
    fmt.Println("-------------------")
    fmt.Println("client id: ", resp.GetClientId())
    fmt.Println("client secret: ", resp.GetClientSecret())
    config = oauth2.Config{
        ClientID:     resp.GetClientId(),
        ClientSecret: resp.GetClientSecret(),
        Scopes:       []string{"openid", "email", "offline"},
        Endpoint: oauth2.Endpoint{
            AuthURL:  "<http://localhost:4000/oauth2/auth>",
            TokenURL: "<http://localhost:4000/oauth2/token>",
        },
        RedirectURL: resp.GetRedirectUris()[0],
    }

    http.HandleFunc("/", handleMain)
    http.HandleFunc("/login/generic_oauth", handleCallback)

    log.Println("Server started on :3001")
    log.Fatal(http.ListenAndServe(":3001", nil))
}

/*
ory tunnel --dev --project xenodochial-dewdney-qdzw45ve2w \
  <http://localhost:3001>
*/
/*
## Testing the OAuth2 flow

1. Run the code by executing `go run main.go`.
2. Open a web browser and navigate to `<http://localhost:3001/>`. This will trigger the `handleMain` function and redirect you to the authorization endpoint.
3. Log in using your credentials and grant access to the requested scopes. This will redirect you back to the callback URL (`<http://localhost:3001/login/generic_oauth>`) with an authorization code in the URL query parameters.
4. The `handleCallback` function will be triggered and will exchange the authorization code for an access token and a refresh token. It will then display the access token and refresh token on the page.

You can also check the console output to see the logs showing the step-by-step process.
*/
this is the complete program which am using to test the flow.