HTML & Python Quickstart

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

Import SDK

You must import our WebJS and Web Component SDKs in order to use the Descope Flows component.

index.html
<!DOCTYPE html>
<html>
  <head>
	<script src="https://unpkg.com/@descope/web-component@x.x.x/dist/index.js"></script>
	<script src="https://unpkg.com/@descope/web-js-sdk@x.x.x/dist/index.umd.js"></script>
  </head>
 
  <body>
    <h1>Log In With Descope Flows</h1>
    <p id="container"></p>
 
	<script></script>
  </body>
</html>

Add Descope SDK and Session Token Logic

To validate whether or not a user is logged in, before deciding to display the login page designed in Flows, use this logic highlighted to the right.

  • persistTokens: this will force existing tokens to be included in all outgoing requests
  • autoRefresh: this will automatically refresh sessions once they are expired, if the refresh token is valid
index.html
<!DOCTYPE html>
<html>
  <head>
	<script src="https://unpkg.com/@descope/web-component@x.x.x/dist/index.js"></script>
	<script src="https://unpkg.com/@descope/web-js-sdk@x.x.x/dist/index.umd.js"></script>
  </head>
 
  <body>
	<h1>Log In With Descope Flows</h1>
    <p id="container"></p>
 
	<script>
		const sdk = Descope({ projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });
 
		const sessionToken = sdk.getSessionToken()
		var notValidToken
		if (sessionToken) {
			notValidToken = sdk.isJwtExpired(sessionToken)
		}
		if (!sessionToken || notValidToken) {
 
		}
	</script>
  </body>
</html>

Add Flows Component

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
  • onSuccess and onError - functions that execute when authentication succeeds or fails
  • theme - "light" or "dark", the default is "light"
  • debug - a boolean that shows a debug widget if true, default is false
  • tenant - where you put the <tenant ID> of the tenant you wish to use in the authentication flow
  • autoRefresh - a boolean that should be true if you wish to automatically refresh your session tokens across multiple pages,
  • redirectUrl - Redirect URL for OAuth and SSO (will be used when redirecting back from the OAuth provider / IdP), or for "Magic Link" and "Enchanted Link" (will be used as a link in the message sent to the the user). When configured within the flow, it overrides the configuration within the Descope console.
  • validateOnBlur - a boolean to configure whether field validation is performed when clicking away from the field (true) or on form submission (false)
  • form - You can optionally pass flow inputs, such as email addresses, names, etc., from your app's frontend to your flow. The configured form inputs can be used within flow screens, actions, and conditionals prefixed with form.
  • Ex: form='{ email: "predefinedname@domain.com", firstName: "test", "customAttribute.test": "aaaa", "myCustomInput": 12 }'
  • client - You can optionally pass flow inputs from your app's frontend to your flow. The configured client inputs can be used within flow actions and conditionals prefixed with client..
  • Ex: client='{ version: "1.2.0" }'
index.html
<!DOCTYPE html>
<html>
  <head>
	<script src="https://unpkg.com/@descope/web-component@x.x.x/dist/index.js"></script>
	<script src="https://unpkg.com/@descope/web-js-sdk@x.x.x/dist/index.umd.js"></script>
  </head>
 
  <body>
	<h1>Log In With Descope Flows</h1>
    <p id="container"></p>
 
	<script>
		const sdk = Descope({ projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });
 
		const sessionToken = sdk.getSessionToken()
		var notValidToken
		if (sessionToken) {
			notValidToken = sdk.isJwtExpired(sessionToken)
		}
		if (!sessionToken || notValidToken) {
			var container = document.getElementById('container');
			container.innerHTML = '<descope-wc project-id="__ProjectID__" flow-id="sign-up-or-in"></descope-wc>';
		}
	</script>
  </body>
</html>

Handle onSuccess and onError Logic

It's important to make sure that you're handling the onSuccess and onError correctly. You will need to use the descope-wc document element and if you are using the autoRefresh token feature in the WebJS SDK, you will need to call sdk.refresh() in onSuccess(). To extract details on the user, you can load the user details from e.detail.user. On successful authentication, the information about the user is returned and accessible with e.detail.user.

Ex: const onSuccess=(e) => { console.log(e.detail.user.name), console.log(e.detail.user.email)};

index.html
<!DOCTYPE html>
<html>
  <head>
	<script src="https://unpkg.com/@descope/web-component@x.x.x/dist/index.js"></script>
	<script src="https://unpkg.com/@descope/web-js-sdk@x.x.x/dist/index.umd.js"></script>
  </head>
 
  <body>
	<h1>Log In With Descope Flows</h1>
    <p id="container"></p>
 
	<script>
		const sdk = Descope({ projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });
 
		const sessionToken = sdk.getSessionToken()
		var notValidToken
		if (sessionToken) {
			notValidToken = sdk.isJwtExpired(sessionToken)
		}
		if (!sessionToken || notValidToken) {
			var container = document.getElementById('container');
			container.innerHTML = '<descope-wc project-id="__ProjectID__" flow-id="sign-up-or-in"></descope-wc>';
 
			const wcElement = document.getElementsByTagName('descope-wc')[0];
			const onSuccess = (e) => {
			console.log(e.detail.user),
			sdk.refresh(),
			window.location.replace("./loggedIn?userId=" + encodeURIComponent(e.detail.user.loginIds))
			};
			const onError = (err) => console.log(err);
 
			wcElement.addEventListener('success', onSuccess);
			wcElement.addEventListener('error', onError);
		}
	</script>
  </body>
</html>

Make Sure Session Persists Across All Pages

On all of your frontend pages, you'll need to make sure that sdk.refresh() is called at the top of each page in <script> tags. Add the following logic to every authenticated page you have in your application.

index.html
<!DOCTYPE html>
<html>
  <head><!-- ... --></head>
 
  <body><!-- ... --></body>
</html>
 
<!-- Add below lines to all your authenticated pages -->
<script src="https://unpkg.com/@descope/web-js-sdk@x.x.x/dist/index.umd.js"></script>
<script>
  sdk.refresh()
  // Rest of your logic ...
</script>

Install Backend SDK

Install the SDK with the following command:

Terminal
pip3 install descope

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.

app.py
from descope import (
    REFRESH_SESSION_TOKEN_NAME,
    SESSION_TOKEN_NAME,
    AuthException,
    DeliveryMethod,
    DescopeClient
)
 
try:
    descope_client = DescopeClient(project_id='__ProjectID__')
except Exception as error:
    print("failed to initialize. Error:")
    print(error)

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.

app.py
def validate_session():
    # Fetch session token from HTTP Authorization Header
    session_token = "xxxx"
 
    try:
        jwt_response = descope_client.validate_session(session_token=session_token)
        print("Successfully validated user session:")
        print(jwt_response)
    except Exception as error:
        print("Could not validate user session. Error:")
        print(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