在 Vue.js 3 中添加身份验证(登录、注销、用户会话、受保护路由),集成 @auth0/auth0-vue SDK,配合 Vite 使用。
Add authentication to Vue.js 3 single-page applications using @auth0/auth0-vue.
auth0-quickstart skill firstbash
npm install @auth0/auth0-vue
For automated setup with Auth0 CLI, see Setup Guide for complete scripts.
For manual setup:
Create .env file:
bash
VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-id
Update src/main.ts:
typescript
import { createApp } from 'vue';
import { createAuth0 } from '@auth0/auth0-vue';
import App from './App.vue';
const app = createApp(App);
app.use(
createAuth0({
domain: import.meta.env.VITE_AUTH0_DOMAIN,
clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
authorizationParams: {
redirect_uri: window.location.origin
}
})
);
app.mount('#app');
Create a login component:
vue
<script setup lang="ts">
import { useAuth0 } from '@auth0/auth0-vue';
const { loginWithRedirect, logout, isAuthenticated, user, isLoading } = useAuth0();
</script>
<template>
<div>
<div v-if="isLoading">Loading...</div>
<div v-else-if="isAuthenticated">
<img :src="user?.picture" :alt="user?.name" />
<span>Welcome, {{ user?.name }}</span>
<button @click="logout({ logoutParams: { returnTo: window.location.origin }})">
Logout
</button>
</div>
<button v-else @click="loginWithRedirect()">
Login
</button>
</div>
</template>
Start your dev server and test the login flow:
bash
npm run dev
MistakeFixForgot to add redirect URI in Auth0 DashboardAdd your application URL (e.g., http://localhost:3000, https://app.example.com) to Allowed Callback URLs in Auth0 DashboardUsing wrong env var prefixVite requires VITE_ prefix, Vue CLI uses VUE_APP_Not handling loading stateAlways check isLoading before rendering auth-dependent UIStoring tokens in localStorageNever manually store tokens - SDK handles secure storage automaticallyMissing createAuth0 plugin registrationMust call app.use(createAuth0({...})) before mounting appAccessing auth before plugin loadsWrap auth-dependent code in v-if="!isLoading"
auth0-quickstart - Basic Auth0 setupauth0-migration - Migrate from another auth providerauth0-mfa - Add Multi-Factor Authenticationauth0-cli - Manage Auth0 resources from the terminalCore Composables:
useAuth0() - Main authentication composableisAuthenticated - Reactive check if user is logged inuser - Reactive user profile informationloginWithRedirect() - Initiate loginlogout() - Log out usergetAccessTokenSilently() - Get access token for API callsCommon Use Cases: