Sign users in to a Vue application
This guide explains how to add Casdoor sign-in to a Vue 2 or Vue 3 application with casdoor-vue-sdk.
Learning outcomes
- Install and initialize casdoor-vue-sdk in Vue 3 and in Vue 2.
- Send users to the Casdoor sign-in and sign-up pages from a component.
What you need
- A Vue 2 or Vue 3 application
- An application in Casdoor, with the callback URL of your Vue application in Redirect URLs
Sample code
- casdoor-python-vue-sdk-example: A Vue frontend with a Python backend
About the Vue SDK
casdoor-vue-sdk wraps casdoor-js-sdk as a Vue plugin. For more control, use casdoor-js-sdk directly.
The plugin is still in development. To ask a question or suggest a change, open an issue.
Install the SDK
# NPM
npm install casdoor-vue-sdk
# Yarn
yarn add casdoor-vue-sdk
Initialize the SDK
The SDK takes the following settings. All of them are strings.
| Parâmetro | Obrigatório | Descrição |
|---|---|---|
| serverUrl | Sim | URL do servidor Casdoor. |
| clientId | Sim | ID do cliente da aplicação. |
| appName | Sim | Nome da aplicação. |
| organizationName | Sim | Organization name. |
| redirectPath | Não | Callback path; default /callback. |
In Vue 3, register the plugin in main.js:
// main.js
import Casdoor from 'casdoor-vue-sdk'
const config = {
serverUrl: "http://localhost:8000",
clientId: "4262bea2b293539fe45e",
organizationName: "casbin",
appName: "app-casnode",
redirectPath: "/callback",
};
const app = createApp(App)
app.use(Casdoor, config)
In Vue 2, the plugin also needs @vue/composition-api:
// main.js
import Casdoor from 'casdoor-vue-sdk'
import VueCompositionAPI from '@vue/composition-api'
const config = {
serverUrl: "http://localhost:8000",
clientId: "4262bea2b293539fe45e",
organizationName: "casbin",
appName: "app-casnode",
redirectPath: "/callback",
};
Vue.use(VueCompositionAPI)
Vue.use(Casdoor, config)
new Vue({
render: h => h(App),
}).$mount('#app')
Add sign-in to a component
Call the SDK from your components, for example to open the sign-in page:
<script>
export default {
name: 'App',
methods: {
login() {
window.location.href = this.getSigninUrl();
},
signup() {
window.location.href = this.getSignupUrl();
}
}
}
</script>
After the user signs in, Casdoor redirects to redirectPath with an authorization code. Send the code to your backend and exchange it for a token there. See Get and verify the access token.
Troubleshooting
Redirects fail after a change of the Vue version
The SDK uses vue-demi to support Vue 2 and Vue 3. If the postinstall hook didn't run, or if you changed the Vue version after you installed the SDK, run:
npx vue-demi-fix