@xepeng/oauth-vue
v1.0.0
Published
Xepeng OAuth 2.0 SDK for Vue.js
Maintainers
Readme
@xepeng/oauth-vue
Xepeng OAuth 2.0 SDK for Vue.js 3 with TypeScript support and PKCE flow.
Installation
npm install @xepeng/oauth-vue
# or
yarn add @xepeng/oauth-vue
# or
pnpm add @xepeng/oauth-vueQuick Start
Using the Composable (Recommended)
<script setup lang="ts">
import { useOAuth } from '@xepeng/oauth-vue'
const oauth = useOAuth({
clientId: 'your-client-id',
redirectUri: 'http://localhost:3000/auth/callback',
scopes: ['profile', 'email'],
})
// Check if already authenticated on mount
onMounted(async () => {
if (oauth.isAuthenticated.value) {
await oauth.getUserInfo()
}
})
</script>
<template>
<div v-if="oauth.isAuthenticated.value">
<p>Welcome, {{ oauth.user?.name }}</p>
<button @click="oauth.logout">Logout</button>
</div>
<div v-else>
<button @click="oauth.login" :disabled="oauth.isLoading.value">
Login with Xepeng
</button>
</div>
</template>Using the Plugin
// main.ts
import { createOAuth } from '@xepeng/oauth-vue'
import { createApp } from 'vue'
const app = createApp(App)
app.use(createOAuth({
clientId: 'your-client-id',
redirectUri: 'http://localhost:3000/auth/callback',
scopes: ['profile', 'email'],
}))<!-- CallbackPage.vue -->
<script setup lang="ts">
import { onMounted } from 'vue'
import { useOAuthPlugin } from '@xepeng/oauth-vue'
import { useRouter } from 'vue-router'
const oauth = useOAuthPlugin()
const router = useRouter()
onMounted(async () => {
await oauth.handleCallback()
router.push('/')
})
</script>
<template>
<p>Loading...</p>
</template>Configuration
interface OAuthConfig {
clientId: string // Required: Your OAuth client ID
clientSecret?: string // Optional: For confidential clients only
redirectUri: string // Required: Registered redirect URI
baseUrl?: string // Default: 'https://staging-api.xepeng.com'
scopes?: string[] // Default: ['profile', 'email']
storage?: 'memory' | 'localStorage' | 'sessionStorage' // Default: 'memory'
autoRefresh?: boolean // Default: true
refreshBuffer?: number // Default: 300 (5 minutes)
}API Reference
useOAuth(config)
The main composable for OAuth authentication.
Returns
{
isAuthenticated: ComputedRef<boolean>
isLoading: Ref<boolean>
user: Ref<UserInfo | null>
error: Ref<Error | null>
login: () => Promise<void>
handleCallback: () => Promise<void>
logout: () => Promise<void>
getAccessToken: () => Promise<string>
refreshAccessToken: () => Promise<void>
revokeTokens: () => Promise<void>
getUserInfo: () => Promise<void>
client: OAuthClient
}Methods
- login() - Redirect user to Xepeng authorization page
- handleCallback() - Handle OAuth callback (call in your callback route)
- logout() - Logout and revoke tokens
- getAccessToken() - Get current access token (auto-refreshes if needed)
- refreshAccessToken() - Manually refresh access token
- revokeTokens() - Revoke all tokens
- getUserInfo() - Fetch user information
OAuthClient
Direct access to the OAuth client for advanced usage.
import { OAuthClient } from '@xepeng/oauth-vue'
const client = new OAuthClient({
clientId: 'your-client-id',
redirectUri: 'http://localhost:3000/auth/callback',
})
// Get authorization URL
const url = await client.getAuthorizationUrl()
// Handle callback
const tokens = await client.handleCallback(callbackUrl)
// Get user info
const user = await client.getUserInfo()
// Check authentication status
const authenticated = client.isAuthenticated()
// Get access token
const token = await client.getAccessToken()
// Logout
client.logout()Making Authenticated Requests
<script setup lang="ts">
import { useOAuth } from '@xepeng/oauth-vue'
const oauth = useOAuth(config)
async function fetchProtectedData() {
const token = await oauth.getAccessToken()
const response = await fetch('https://api.example.com/protected', {
headers: {
Authorization: `Bearer ${token}`,
},
})
return response.json()
}
</script>PKCE Flow
This SDK uses PKCE (Proof Key for Code Exchange) for secure authentication, which is recommended for public clients (SPAs, mobile apps).
The flow:
- Authorization: User is redirected to Xepeng with a code challenge
- Callback: Exchange authorization code + verifier for tokens
- Access: Use access token to authenticate requests
- Refresh: Automatically refresh tokens before expiry
Error Handling
<script setup lang="ts">
import { watch } from 'vue'
import { useOAuth, OAuthError } from '@xepeng/oauth-vue'
const oauth = useOAuth(config)
watch(() => oauth.error.value, (error) => {
if (error) {
if (error instanceof OAuthError) {
console.error(`OAuth Error [${error.code}]:`, error.message)
} else {
console.error('Error:', error)
}
}
})
</script>License
MIT
