bright-policeman-41717
05/31/2023, 4:00 PMbright-policeman-41717
05/31/2023, 4:22 PMoAuth2Client := *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")bright-policeman-41717
05/31/2023, 4:47 PMlively-scientist-17848
05/31/2023, 4:53 PMemail scope for the email to be present on the id_tokenbright-policeman-41717
05/31/2023, 4:54 PMlively-scientist-17848
05/31/2023, 4:55 PMoAuth2Client.SetScope("openid email")lively-scientist-17848
05/31/2023, 4:56 PMbright-policeman-41717
05/31/2023, 5:10 PMbright-policeman-41717
05/31/2023, 5:10 PMbright-policeman-41717
05/31/2023, 5:10 PMUser Info: {"error":"request_unauthorized","error_description":"The request could not be authorized. Check that you provided valid credentials in the right format."}bright-policeman-41717
05/31/2023, 5:12 PM<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>bright-policeman-41717
05/31/2023, 5:17 PMpackage 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.
*/bright-policeman-41717
05/31/2023, 5:18 PM