Vue.js & Java Quickstart

This is a quickstart guide to help you integrate Descope with your Vue.js & Java application. Follow the steps below to get started.

Install Frontend SDK

Install the SDK with the following command:

Terminal
npm i --save @descope/vue-sdk

Add Vue SDK to your Application

Start by importing Descope and add the Vue SDK to your application. You will need your Project ID from Project Settings in the Descope Console.

Note

You can also add the optional baseUrl parameter if you're utilizing a CNAME within your Descope project (ex: https://auth.company.com).

App.vue
import { createApp } from "vue";
import App from "@/App.vue";
import router from "./router";
import descope, { getSdk } from "@descope/vue-sdk";
 
const app = createApp(App);
app.use(router);
 
app.use(descope, {
  projectId: '__ProjectID__',
  baseUrl: "<base url>", // Optional
});
 
const sdk = getSdk();
sdk?.onSessionTokenChange((newSession) => {
  // here you can implement custom logic when the session is changing
});
 
app.mount("#app");

Use the SDK to Render a Specific Flow

To trigger the Descope Flow, you will need to add this component. The screens you've customized in your Flow will appear here. You can also customize the component with the following:

  • flowId: ID of the flow you wish to use
  • @success and @error: functions that execute when authentication succeeds or fails

Note

For the full list of component customization options, refer to our Descope Components Customization Doc.

Login.vue
<template>
  <div class="wrapper">
    <p v-if="isLoading">Loading...</p>
    <div v-else-if="isAuthenticated">
      <h1>You are authenticated</h1>
    </div>
    <Descope
      v-else
      :flowId="sign-up-or-in" // can be any flow id
      @error="handleError"
      @success="handleSuccess"
      :errorTransformer="errorTransformer"
    />
  </div>
</template>
 
<script setup>
import { Descope, useSession } from "@descope/vue-sdk";
const { isLoading, isAuthenticated } = useSession();
 
const handleError = (e) => {
  console.log("Got error", e);
};
 
const handleSuccess = (e) => {
  console.log("Logged in", e);
};
 
const errorTransformer = (error) => {
  const translationMap = {
    SAMLStartFailed: "Failed to start SAML flow",
  };
  return translationMap[error.type] || error.text;
};
</script>

Utilize the Vue SDK Hooks and Functions

Descope provides many different hooks to check if the user is authenticated, session is loading etc. You can use these to customize the user experience:

  • isAuthenticated: Boolean for the authentication state of the current user session.
  • isSessionLoading: Boolean for the loading state of the session. Can be used to display a "loading" message while the session is still loading.
  • useUser: Returns information about the currently authenticated user.
  • logout: Logs out the currently authenticated user.

Note

For the full list of available hooks and functions, refer to the Auth Helpers Doc.

Home.vue
<template>
	<div v-if="isSessionLoading || isUserLoading">Loading ...</div>
	<div v-else-if="isAuthenticated">
		<div>Hello {{ user?.name }}</div>
		<button @click="logout">Logout</button>
	</div>
	<div v-else>You are not logged in</div>
</template>
 
<script setup>
import { useDescope, useSession, useUser } from '@descope/vue-sdk';
 
const { isAuthenticated, isSessionLoading } = useSession();
const { user, isUserLoading } = useUser();
const { logout } = useDescope();
</script>

Pass Session Token to Server API

Use getSessionToken to retrieve the session token, and pass it in the Authorization header of your API requests for server-side validation.

App.vue
import { getSessionToken } from '@descope/vue-sdk';
 
// example fetch call with http header
export const fetchData = async () => {
	const sessionToken = getSessionToken();
	const res = await fetch('/path/to/server/api', {
		headers: {
			Authorization: `Bearer ${sessionToken}`
		}
	});
	// ... use res
};

At this point, you're done with the frontend. If you would like to also handle Session Management in your backend, keep on reading!

Install Backend SDK

Install the SDK by including the SDK in your pom.xml file (for installation via Maven).

pom.xml
<dependency>
	<artifactId>java-sdk</artifactId>
	<groupId>com.descope</groupId>
	<version>1.0.25</version>
</dependency>

Import and Setup Backend SDK

You'll need import and setup all of the packages from the SDK.

If you're using a CNAME with your Descope project, make sure to export the Base URL (e.g. export DESCOPE_BASE_URI="https://api.descope.com") when initializing descope_client.

Application.java
package com.descope.java_sample_app;
 
// descope imports start
import com.descope.client.*;
import com.descope.exception.DescopeException;
import com.descope.model.jwt.Token;
import com.descope.sdk.auth.AuthenticationService;
// descope imports end
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
 
@SpringBootApplication
@RestController
public class JavaSampleAppApplication {
 
	public static void main(String[] args) {
		SpringApplication.run(JavaSampleAppApplication.class, args);
	}
 
}

Implement Session Validation

You will need to then fetch the session token from the Authorization header of each request, and use the SDK to validate the token.

The frontend SDK will store the session token in either a cookie or your browser's local storage. If using a cookie, the token will be sent to your app server automatically with every request.

Application.java
@SpringBootApplication
@RestController
public class JavaSampleAppApplication {
 
	public static void main(String[] args) {
		SpringApplication.run(JavaSampleAppApplication.class, args);
	}
	
	public void validateSession(String sessionToken, String refreshToken) {
		var descopeClient = new DescopeClient(Config.builder().projectId("__ProjectID__").build());
 
		// Validate the session. Will return an error if expired
		AuthenticationService as = descopeClient.getAuthenticationServices().getAuthService();
		try {
			Token t = as.validateSessionWithToken(sessionToken);
		} catch (DescopeException de) {
			// Handle the unauthorized error
		}
 
		// If ValidateSessionWithRequest raises an exception, you will need to refresh the session using
		try {
			Token t = as.refreshSessionWithToken(refreshToken);
		} catch (DescopeException de) {
			// Handle the unauthorized error
		}
 
		// Alternatively, you could combine the two and
		// have the session validated and automatically refreshed when expired
		try {
			Token t = as.validateAndRefreshSessionWithTokens(sessionToken, refreshToken);
		} catch (DescopeException de) {
			// unauthorized error
		}
	}
	
}

Congratulations

Now that you've got the authentication down, go focus on building out the rest of your app!


Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?

Customize

Now that you have the end-to-end application working, you can choose to configure and personalize many different areas of Descope, including your brand, style, custom user authentication journeys, etc. We recommend starting with customizing your user-facing screens, such as signup and login.

Was this helpful?

On this page