Setting up OAuth2 client configuration
This guide shows how to initialize your application to work with Ory's OAuth2 server. You'll configure the basic setup required before implementing authentication flows.
- Express.js
- Go
1. Install dependencies
npm install express-session openid-client
2. Initialize the OpenID Connect client
This code sets up the OpenID client by discovering the Ory OAuth2 server endpoints and configuring your client credentials.
index.js
import * as client from "openid-client"
import express from "express"
const app = express()
// Configure environment variables
const ORY_PROJECT_SLUG = process.env.ORY_PROJECT_SLUG
const OAUTH_CLIENT_ID = process.env.OAUTH_CLIENT_ID
const OAUTH_CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET
let config
;(async () => {
try {
// Create server URL (Ory's issuer URL)
const server = new URL(`https://${ORY_PROJECT_SLUG}.projects.oryapis.com`)
// Use discovery to fetch the server metadata and create a configuration
config = await client.discovery(
server,
OAUTH_CLIENT_ID,
OAUTH_CLIENT_SECRET,
client.ClientSecretBasic(OAUTH_CLIENT_SECRET),
)
console.log("Discovery successful")
} catch (error) {
console.error("Discovery error:", error)
}
})()
1. Install the Go OAuth2 package
go get golang.org/x/oauth2
2. Initialize the OpenID Connect client
This code sets up the client by discovering the Ory OAuth2 server endpoints and configuring your client credentials.
main.go
package main
import (
"fmt"
"os"
"golang.org/x/oauth2"
)
// Configuration
var (
// Replace these with your own values
clientID = os.Getenv("OAUTH_CLIENT_ID")
clientSecret = os.Getenv("OAUTH_CLIENT_SECRET")
projectSlug = os.Getenv("ORY_PROJECT_SLUG")
redirectURL = os.Getenv("OAUTH_REDIRECT_URI")
port = "3000"
// Ory OAuth2 endpoints
oryEndpoint = oauth2.Endpoint{
AuthURL: fmt.Sprintf("https://%s.projects.oryapis.com/oauth2/auth", projectSlug),
TokenURL: fmt.Sprintf("https://%s.projects.oryapis.com/oauth2/token", projectSlug),
}
// OAuth2 config
oauthConfig = &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: []string{"openid", "offline_access", "email"},
Endpoint: oryEndpoint,
}
// In-memory session store (replace with a proper session store in production)
sessions = make(map[string]Session)
)
// Session represents user session data
type Session struct {
State string
CodeVerifier string
Token *oauth2.Token
UserInfo map[string]interface{}
}