2

I'm trying to integrate Auth0 to my SPA. I'm embedding the Lock feature, so it handles authentication by itself.

I can login, and the Lock feature works fine, however I'm trying to save the accessToken and the idToken returned by Lock to a cookie. I'm using react-cookie for that.

This is my code:

import React, { useEffect } from "react";
import Auth0Lock from "auth0-lock";
import AUTH_CONFIG from "../../config/auth0";
import moment from "moment";
import { useCookies } from "react-cookie";
import history from "../../utils/history";

export default function Lock() {
    const [cookies, setCookie] = useCookies(["token"]);

    const lock = new Auth0Lock(AUTH_CONFIG.clientId, AUTH_CONFIG.domain, {
        auth: {
            responseType: "token id_token",
            sso: false
        },
        container: AUTH_CONFIG.container,
        theme: {
            primaryColor: "#3a99d8"
        }
    });

    useEffect(() => {
        if (cookies.token && cookies.token.expires < moment()._d) {
            history.push("/");
        }
        lock.show();
    }, [cookies]);

    lock.on("authenticated", authResult => {
        let expiresAt = moment(
            authResult.expiresIn * 1000 + new Date().getTime()
        );
        setCookie(
            "token",
            {
                access_token: authResult.accessToken,
                id_token: authResult.idToken
            },
            { path: "/", expires: expiresAt._d, secure: true }
        );
    });

    return (
        <div>
            <div id={AUTH_CONFIG.container} style={{ marginTop: "32px" }} />
        </div>
    );
}

So, after authenticating, the lock.on event listener is called. I can see that it works fine, however the setCookie hook doesn't save the cookie. I've already console.log(authResult) and can confirm that it returns the appropriate values, but the setCookie doesn't save anything. Exploring my browser storage, I can see that no cookie is saved.

Does anybody have a clue why it doesn't save the token cookie?

Thanks in advance

Edit: I found the issue. I was setting secure: true, however I was trying to access it thru http://localhost, which is not secure.

Otavio Bonder
  • 1,789
  • 4
  • 17
  • 35

0 Answers0