I have a simple demo app based on SvelteKit in which I am attempting to use auth0 for authentication. The initial authentication works as expected, and is executed like this (I also have a stores.js
file where writable stores are created to hold the state of user
, isAutheniticated
, and popupOpen
, and an auth_config.js
file to hold my auth0 credentials.):
// authService.js
import { createAuth0Client } from "@auth0/auth0-spa-js";
import { user, isAuthenticated, popupOpen } from "./store";
import config from "../auth_config";
async function createClient() {
let auth0Client = await createAuth0Client({
domain: config.domain,
clientId: config.clientId
});
return auth0Client;
}
async function loginWithPopup(client, options) {
let c = await client.loginWithPopup(options);
user.set(await client.getUser());
isAuthenticated.set(true);
}
function logout(client) {
return client.logout();
}
//+layout.svelte
<script>
import { onMount } from "svelte";
import auth from "../authService";
import { isAuthenticated, user } from "../store";
let auth0Client;
onMount(async () => {
auth0Client = await auth.createClient();
isAuthenticated.set(await auth0Client.isAuthenticated());
user.set(await auth0Client.getUser());
});
function login() {
auth.loginWithPopup(auth0Client);
}
function logout() {
auth.logout(auth0Client);
}
</script>
{#if $isAuthenticated}
<a class="nav-link" href="/#" on:click="{logout}">Log Out</a>
{:else}
<a class="nav-link" href="/#" on:click="{login}">Log In</a>
{/if}
<slot />
And when I login I see a cookie named auth0.MY_CLIENT_ID.is.authenticated
and its value is "true".
However, when I refresh the page, the cookie is removed. When I click the login link, the auth0 popup briefly displays but then closes itself and I am logged in again, and the cookie is set again.
It seems to me I am doing something wrong, since the auth0 client knows I am logged in and does not ask for my credentials again, but my app is not aware I am logged in. What is the proper way to hang on to the session cookie so that it does not appear that I am logged out when I refresh?
Researching some more, I came across this very helpful post from the auth0 message boards.
Allowing 3rd party cookies "solved" my problem, but obviously I don't want my end users to have to do that. Instead, I enabled refresh tokens within my application settings on auth0.com, and then within my client I enabled local storage and refresh tokens:
Now my authentication survives a refresh (even with 3rd party cookies blocked).