API calls
#### Step 0: Endpoints
The OAuth2 base URLs are:
* **Testnet**: <https://oauth2.testnet.burnt.com/>
* **Mainnet**: <https://oauth2.burnt.com/>
Set `VITE_XION_OAUTH2_SERVER_URL` (frontend) or `XION_OAUTH2_SERVER_URL` (backend) to the base URL for your target network **without a trailing slash** (for example, `https://oauth2.testnet.burnt.com`). The examples below use testnet defaults and resolve discovery paths with `new URL()` to avoid double slashes.
#### Step 1: Discovery - Get OAuth2 Server Information
Before starting the OAuth2 flow, you need to discover the OAuth2 server's endpoints. This is done by fetching the `.well-known/oauth-authorization-server` endpoint:
```typescript
async function getOAuthServerInfo(): Promise<OAuthServerInfo> {
const serverUrl = 'https://oauth2.testnet.burnt.com'
const response = await fetch(
new URL('.well-known/oauth-authorization-server', serverUrl).toString()
)
if (!response.ok) {
throw new Error('Failed to fetch OAuth server info')
}
return response.json()
}
```
The response includes:
* `issuer`: The OAuth2 server identifier
* `authorization_endpoint`: URL for the authorization endpoint
* `token_endpoint`: URL for the token exchange endpoint
* `scopes_supported`: Available OAuth2 scopes
#### Step 2: Authorization - Build Authorization URL
Build the authorization URL with standard OAuth2 parameters:
**For Public Clients (with PKCE):**
```typescript
// Generate PKCE code verifier and challenge
const codeVerifier = generateCodeVerifier() // 32-byte random string, base64url encoded
const codeChallenge = await generateCodeChallenge(codeVerifier) // SHA256 hash of verifier
// Generate state for CSRF protection
const state = generateRandomString()
// Build authorization URL
const authUrl = new URL(serverInfo.authorization_endpoint)
authUrl.searchParams.set('client_id', clientId)
authUrl.searchParams.set('redirect_uri', redirectUri)
authUrl.searchParams.set('response_type', 'code')
authUrl.searchParams.set('code_challenge', codeChallenge)
authUrl.searchParams.set('code_challenge_method', 'S256')
authUrl.searchParams.set('scope', 'xion:transactions:submit')
authUrl.searchParams.set('state', state)
// Redirect user to authorization URL
window.location.href = authUrl.toString()
```
**For Confidential Clients:**
```typescript
// Generate state for CSRF protection
const state = generateRandomString()
// Build authorization URL (PKCE optional for confidential clients)
const authUrl = new URL(serverInfo.authorization_endpoint)
authUrl.searchParams.set('client_id', clientId)
authUrl.searchParams.set('redirect_uri', redirectUri)
authUrl.searchParams.set('response_type', 'code')
authUrl.searchParams.set('scope', 'xion:transactions:submit')
authUrl.searchParams.set('state', state)
// Redirect user to authorization URL
window.location.href = authUrl.toString()
```
**OAuth2 Authorization Parameters:**
* `client_id`: Your OAuth2 client ID
* `redirect_uri`: Must **exactly equal** the bound Treasury's on-chain `redirect_url` (the single source of truth). Authorization is rejected if they differ.
* `response_type`: Always `"code"` for Authorization Code flow
* `code_challenge`: (Public Clients) Base64url-encoded SHA256 hash of code\_verifier
* `code_challenge_method`: (Public Clients) Always `"S256"` for SHA256
* `scope`: Verona's OAuth2 Protected API scopes (e.g., `"xion:transactions:submit"`)
* `state`: Random string for CSRF protection
#### Step 3: Callback - Handle Authorization Code
After the user authorizes your application, they'll be redirected back to your `redirect_uri` with an authorization code:
```typescript
// Extract code and state from URL
const urlParams = new URLSearchParams(window.location.search)
const code = urlParams.get('code')
const state = urlParams.get('state')
const error = urlParams.get('error')
if (error) {
// Handle authorization error
console.error('Authorization error:', error)
return
}
if (!code) {
// Handle missing code
console.error('No authorization code received')
return
}
// Verify state parameter (CSRF protection)
const storedState = sessionStorage.getItem('oauth_state')
if (state !== storedState) {
throw new Error('Invalid state parameter. Possible CSRF attack.')
}
```
#### Step 4: Token Exchange - Exchange Code for Access Token
Exchange the authorization code for an access token:
**For Public Clients (with PKCE):**
Send the token request as **`application/x-www-form-urlencoded`** (standard for OAuth 2.0 token endpoints):
```typescript
async function exchangeCodeForToken(code: string): Promise<TokenInfo> {
const serverInfo = await getOAuthServerInfo()
const codeVerifier = sessionStorage.getItem('oauth_code_verifier') // Retrieved from Step 2
const response = await fetch(serverInfo.token_endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier!, // PKCE: code verifier replaces client_secret
client_id: clientId,
}),
})
if (!response.ok) {
throw new Error('Token exchange failed')
}
const tokens = await response.json()
return {
accessToken: tokens.access_token,
expiresIn: tokens.expires_in,
tokenType: tokens.token_type,
refreshToken: tokens.refresh_token,
}
}
```
**For Confidential Clients (typically without PKCE; PKCE may still be used in addition to `client_secret` if your client is configured for it):**
```typescript
async function exchangeCodeForToken(code: string): Promise<TokenInfo> {
const serverInfo = await getOAuthServerInfo()
const response = await fetch(serverInfo.token_endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri, // Must match the redirect_uri used in the authorization request
client_id: clientId,
client_secret: clientSecret, // Stored securely on server
}),
})
if (!response.ok) {
throw new Error('Token exchange failed')
}
const tokens = await response.json()
return {
accessToken: tokens.access_token,
expiresIn: tokens.expires_in,
tokenType: tokens.token_type,
refreshToken: tokens.refresh_token,
}
}
```
**Refreshing an access token**
When the provider returns a `refresh_token`, you can request a new access token:
```typescript
async function refreshAccessToken(refreshToken: string): Promise<TokenInfo> {
const serverInfo = await getOAuthServerInfo()
const body = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
})
// Confidential clients: append client_secret to the same form body if your client requires it.
const response = await fetch(serverInfo.token_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
})
if (!response.ok) throw new Error('Token refresh failed')
const tokens = await response.json()
return {
accessToken: tokens.access_token,
expiresIn: tokens.expires_in,
tokenType: tokens.token_type,
refreshToken: tokens.refresh_token ?? refreshToken,
}
}
```
**OAuth2 token request parameters**
* `grant_type`: `"authorization_code"` for the initial exchange, or `"refresh_token"` to rotate access tokens
* `code`: Authorization code (authorization\_code grant only)
* `redirect_uri`: Must match the `redirect_uri` used in the authorization request, which must equal the Treasury `redirect_url` (authorization\_code grant only)
* `client_id`: Your OAuth2 client ID
* `client_secret`: Confidential clients only (authorization\_code or refresh\_token, depending on provider policy)
* `code_verifier`: Public clients with PKCE (authorization\_code grant)
* `refresh_token`: Issued refresh token (refresh\_token grant)
### 4.2 Frontend Public Client Example
This example demonstrates a complete frontend OAuth2 integration using a Public Client with PKCE.
Example repository: [xion-oauth2-app-demo/examples/frontend+public\_client](https://github.com/burnt-labs/xion-oauth2-app-demo/tree/main/examples/frontend+public_client)
Following are some of major OAuth2 utility functions for the frontend Public Client example.
**Complete OAuth2 Utility Functions:**
```typescript
// utils/oauth.ts
import type { TokenInfo, OAuthServerInfo } from '@/types'
const STORAGE_KEY_TOKEN = 'xion_oauth_token'
const STORAGE_KEY_EXPIRATION = 'xion_oauth_expiration'
const STORAGE_KEY_REFRESH = 'xion_oauth_refresh_token'
const STORAGE_KEY_CODE_VERIFIER = 'xion_oauth_code_verifier'
const STORAGE_KEY_STATE = 'xion_oauth_state'
export function getOAuthServerUrl(): string {
return import.meta.env.VITE_XION_OAUTH2_SERVER_URL || 'https://oauth2.testnet.burnt.com'
}
export function getClientId(): string {
return import.meta.env.VITE_XION_OAUTH2_CLIENT_ID || ''
}
export function getRedirectUri(): string {
return `${window.location.origin}/callback`
}
export async function getOAuthServerInfo(): Promise<OAuthServerInfo> {
const serverUrl = getOAuthServerUrl()
const response = await fetch(
new URL('.well-known/oauth-authorization-server', serverUrl).toString()
)
if (!response.ok) {
throw new Error('Failed to fetch OAuth server info')
}
return response.json()
}
// Generate PKCE code verifier (32 random bytes, base64url encoded)
export function generateCodeVerifier(): string {
const array = new Uint8Array(32)
crypto.getRandomValues(array)
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '')
}
// Generate PKCE code challenge (SHA256 hash of verifier, base64url encoded)
export async function generateCodeChallenge(verifier: string): Promise<string> {
const encoder = new TextEncoder()
const data = encoder.encode(verifier)
const hash = await crypto.subtle.digest('SHA-256', data)
return btoa(String.fromCharCode(...new Uint8Array(hash)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '')
}
// Start OAuth2 authorization flow
export async function startAuthorization(): Promise<void> {
const serverInfo = await getOAuthServerInfo()
const clientId = getClientId()
const redirectUri = getRedirectUri()
if (!clientId) {
throw new Error('Client ID is not configured')
}
// Generate PKCE code verifier and challenge
const codeVerifier = generateCodeVerifier()
sessionStorage.setItem(STORAGE_KEY_CODE_VERIFIER, codeVerifier)
const codeChallenge = await generateCodeChallenge(codeVerifier)
// Generate state parameter for CSRF protection
const state = generateCodeVerifier()
sessionStorage.setItem(STORAGE_KEY_STATE, state)
// Build authorization URL with PKCE parameters
const authUrl = new URL(serverInfo.authorization_endpoint)
authUrl.searchParams.set('client_id', clientId)
authUrl.searchParams.set('redirect_uri', redirectUri)
authUrl.searchParams.set('response_type', 'code')
authUrl.searchParams.set('code_challenge', codeChallenge)
authUrl.searchParams.set('code_challenge_method', 'S256')
authUrl.searchParams.set('scope', 'xion:transactions:submit')
authUrl.searchParams.set('state', state)
window.location.href = authUrl.toString()
}
// Exchange authorization code for access token
export async function exchangeCodeForToken(
code: string,
state?: string
): Promise<TokenInfo> {
const serverInfo = await getOAuthServerInfo()
const clientId = getClientId()
const redirectUri = getRedirectUri()
// Retrieve PKCE code verifier from session storage
const codeVerifier = sessionStorage.getItem(STORAGE_KEY_CODE_VERIFIER)
if (!codeVerifier) {
throw new Error('Code verifier not found. Please restart the authorization flow.')
}
// Verify state parameter for CSRF protection
if (state) {
const storedState = sessionStorage.getItem(STORAGE_KEY_STATE)
if (!storedState || storedState !== state) {
sessionStorage.removeItem(STORAGE_KEY_CODE_VERIFIER)
sessionStorage.removeItem(STORAGE_KEY_STATE)
throw new Error('Invalid state parameter. Possible CSRF attack.')
}
}
// Exchange authorization code for access token using PKCE
const response = await fetch(serverInfo.token_endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier, // PKCE: code verifier replaces client_secret
client_id: clientId,
}),
})
if (!response.ok) {
const error = await response.json().catch(() => ({ error: 'Token exchange failed' }))
sessionStorage.removeItem(STORAGE_KEY_CODE_VERIFIER)
sessionStorage.removeItem(STORAGE_KEY_STATE)
throw new Error(error.error || 'Token exchange failed')
}
const tokens = await response.json()
const expiresIn = tokens.expires_in || 3600
const expiration = Date.now() + expiresIn * 1000
const tokenInfo: TokenInfo = {
accessToken: tokens.access_token,
expiresIn,
expiration,
tokenType: tokens.token_type,
refreshToken: tokens.refresh_token,
}
saveTokenInfo(tokenInfo)
// Clean up PKCE and state from session storage
sessionStorage.removeItem(STORAGE_KEY_CODE_VERIFIER)
sessionStorage.removeItem(STORAGE_KEY_STATE)
return tokenInfo
}
/** Optional: obtain a new access token using refresh_token from a prior exchange. */
export async function refreshAccessToken(): Promise<TokenInfo> {
const refreshToken = localStorage.getItem(STORAGE_KEY_REFRESH)
if (!refreshToken) {
throw new Error('No refresh token stored. Run the authorization flow again.')
}
const serverInfo = await getOAuthServerInfo()
const clientId = getClientId()
const response = await fetch(serverInfo.token_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
}),
})
if (!response.ok) {
throw new Error('Token refresh failed')
}
const tokens = await response.json()
const expiresIn = tokens.expires_in || 3600
const expiration = Date.now() + expiresIn * 1000
const tokenInfo: TokenInfo = {
accessToken: tokens.access_token,
expiresIn,
expiration,
tokenType: tokens.token_type,
refreshToken: tokens.refresh_token ?? refreshToken,
}
saveTokenInfo(tokenInfo)
return tokenInfo
}
// Token storage utilities
export function saveTokenInfo(tokenInfo: TokenInfo): void {
localStorage.setItem(STORAGE_KEY_TOKEN, tokenInfo.accessToken)
localStorage.setItem(STORAGE_KEY_EXPIRATION, tokenInfo.expiration.toString())
if (tokenInfo.refreshToken) {
localStorage.setItem(STORAGE_KEY_REFRESH, tokenInfo.refreshToken)
}
}
export function getTokenInfo(): TokenInfo | null {
const accessToken = localStorage.getItem(STORAGE_KEY_TOKEN)
const expiration = localStorage.getItem(STORAGE_KEY_EXPIRATION)
if (!accessToken || !expiration) {
return null
}
const expirationTime = parseInt(expiration, 10)
if (Date.now() >= expirationTime) {
clearTokenInfo()
return null
}
const expiresIn = Math.floor((expirationTime - Date.now()) / 1000)
return {
accessToken,
expiration: expirationTime,
expiresIn: expiresIn > 0 ? expiresIn : 0,
refreshToken: localStorage.getItem(STORAGE_KEY_REFRESH) ?? undefined,
}
}
export function clearTokenInfo(): void {
localStorage.removeItem(STORAGE_KEY_TOKEN)
localStorage.removeItem(STORAGE_KEY_EXPIRATION)
localStorage.removeItem(STORAGE_KEY_REFRESH)
}
```
**Callback Component Example(Frontend Public Client):**
```typescript
// components/Callback.tsx
import { useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { exchangeCodeForToken } from '@/utils/oauth'
export function Callback() {
const [searchParams] = useSearchParams()
const navigate = useNavigate()
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
const handleCallback = async () => {
const code = searchParams.get('code')
const state = searchParams.get('state')
const errorParam = searchParams.get('error')
if (errorParam) {
setError(`Authorization error: ${errorParam}`)
setIsLoading(false)
return
}
if (!code) {
setError('No authorization code received')
setIsLoading(false)
return
}
try {
await exchangeCodeForToken(code, state || undefined)
navigate('/dashboard', { replace: true })
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to exchange code for token')
setIsLoading(false)
}
}
handleCallback()
}, [searchParams, navigate])
if (isLoading) {
return <div>Processing authorization...</div>
}
if (error) {
return <div>Error: {error}</div>
}
return null
}
```
**Key Points for Frontend Implementation:**
1. **PKCE is Required**: Public clients must use PKCE for security. The code verifier is generated client-side and never sent to the server until token exchange.
2. **State Parameter**: Always use a state parameter for CSRF protection. Store it in sessionStorage and verify it in the callback.
3. **Token Storage**: Store access tokens securely. Use localStorage for persistence, but be aware of XSS risks. Consider using httpOnly cookies for production applications. If the token response includes a `refresh_token`, persist it separately (as in the example above) so you can rotate access tokens without a full login.
4. **Token Expiration**: Prefer calling `grant_type=refresh_token` when you have a stored refresh token; otherwise re-run the authorization flow when the access token expires.
5. **`TokenInfo` type**: Extend your app's `TokenInfo` type with an optional `refreshToken?: string` if you follow the sample storage helpers.
### 4.3 Backend Confidential Client Example
This example demonstrates a complete backend OAuth2 integration using a Confidential Client with server-side token exchange.
Example repository: [xion-oauth2-app-demo/examples/backend+confidential\_client](https://github.com/burnt-labs/xion-oauth2-app-demo/tree/main/examples/backend+confidential_client)
Following are some of major OAuth2 utility functions for the backend Confidential Client example.
**OAuth2 Configuration (Server-side):**
```typescript
// lib/oauth-config.ts
export function getOAuthServerUrl(): string {
return process.env.XION_OAUTH2_SERVER_URL || 'https://oauth2.testnet.burnt.com'
}
export function getClientId(): string {
const clientId = process.env.XION_OAUTH2_CLIENT_ID
if (!clientId) {
throw new Error('XION_OAUTH2_CLIENT_ID is not configured')
}
return clientId
}
export function getClientSecret(): string {
const clientSecret = process.env.XION_OAUTH2_CLIENT_SECRET
if (!clientSecret) {
throw new Error('XION_OAUTH2_CLIENT_SECRET is not configured')
}
return clientSecret
}
export function getRedirectUri(req?: NextApiRequest): string {
const appUrl = getAppBaseUrl(req) // Your application base URL
return `${appUrl}/api/auth/callback`
}
export async function getOAuthServerInfo(): Promise<OAuthServerInfo> {
const serverUrl = getOAuthServerUrl()
const response = await fetch(
new URL('.well-known/oauth-authorization-server', serverUrl).toString()
)
if (!response.ok) {
throw new Error('Failed to fetch OAuth server info')
}
return response.json()
}
```
**Authorization Endpoint (Initiate OAuth2 Flow):**
```typescript
// pages/api/auth/login.ts (Next.js API route example)
import type { NextApiRequest, NextApiResponse } from 'next'
import { getOAuthServerInfo, getClientId, getRedirectUri } from '@/lib/oauth-config'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' })
}
try {
const serverInfo = await getOAuthServerInfo()
const clientId = getClientId()
const redirectUri = getRedirectUri(req)
// Generate state parameter for CSRF protection
const state = generateRandomString()
// Store state in httpOnly cookie
res.setHeader('Set-Cookie', [
`oauth_state=${state}; Path=/; HttpOnly; Same프로젝트로 돌아가기