2

我正在尝试将 Auth0 集成到我的 SPA 中。我嵌入了锁定功能,因此它自己处理身份验证。

我可以登录,并且 Lock 功能工作正常,但是我正在尝试将 Lock 返回的accessTokenidToken返回的内容保存到 cookie 中。我正在react-cookie为此使用。

这是我的代码:

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>
    );
}

因此,在进行身份验证后,将lock.on调用事件侦听器。我可以看到它工作正常,但是setCookie钩子并没有保存 cookie。我已经console.log(authResult)并且可以确认它返回了适当的值,但是setCookie并没有保存任何东西。探索我的浏览器存储,我可以看到没有保存任何 cookie。

有人知道为什么它不保存tokencookie吗?

提前致谢

编辑:我发现了问题。我正在设置secure: true,但是我试图通过它访问它http://localhost,这是不安全的。

4

0 回答 0