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
const session = require("express-session")
const client = require("openid-client")
const app = express()
// Session setup to store PKCE and state values
app.use(
session({
secret: "your-session-secret",
resave: false,
saveUninitialized: true,
}),
)
// Configure environment variables
const ORY_PROJECT_SLUG = "your-project-slug"
const OAUTH_CLIENT_ID = "your-client-id"
const OAUTH_CLIENT_SECRET = "your-client-secret"
// Initialize OpenID client configuration
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("ORY_CLIENT_ID")
clientSecret = os.Getenv("ORY_CLIENT_SECRET")
projectSlug = os.Getenv("ORY_PROJECT_SLUG")
redirectURL = "http://localhost:8080/callback"
port = "8080"
// 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{}
}