简体   繁体   English

Auth0 "JWT 字符串必须包含两个点"

[英]Auth0 "The JWT string must contain two dots"

I'm currently using Vue3 and have integrated Auth0-spa-js from https://github.com/auth0/auth0-spa-js .我目前正在使用 Vue3 并集成了来自https://github.com/auth0/auth0-spa-js的 Auth0-spa-js。 This works great.这很好用。

I'm sending requests to a PHP API backend through Axios, passing in the access token as a GET parameter called token.我正在通过 Axios 向 PHP API 后端发送请求,将访问令牌作为称为令牌的 GET 参数传递。

Server side I get an exception "The JWT string must contain two dots" after setting up steps from https://github.com/auth0/auth0-PHP .服务器端在设置来自https://github.com/auth0/auth0-PHP的步骤后,我得到一个异常“JWT 字符串必须包含两个点”。 I've installed the requirements, guzzle and dotenv, etc. Currently on PHP 7.4.2.我已经安装了要求、guzzle 和 dotenv 等。目前在 PHP 7.4.2。

// useAuth0.js
// to login and maintain Auth state

import createAuth0Client from "@auth0/auth0-spa-js";
import { reactive } from "vue";

export const AuthState = reactive({
  user: null,
  loading: false,
  isAuthenticated: null,
  auth0: null,
});

const config = {
  domain: import.meta.env.VITE_AUTH0_DOMAIN,
  client_id: import.meta.env.VITE_AUTH0_CLIENT_ID,
};

export const useAuth0 = (state) => {
  const handleStateChange = async () => {
    state.isAuthenticated = !!(await state.auth0.isAuthenticated());
    state.user = await state.auth0.getUser();
    state.loading = false;
  };

  const initAuth = () => {
    state.loading = true;
    createAuth0Client({
      domain: config.domain,
      client_id: config.client_id,
      cacheLocation: "localstorage",
      redirect_uri: window.location.origin,
    }).then(async (auth) => {
      state.auth0 = auth;
      await handleStateChange();
    });
  };

  const login = async () => {
    await state.auth0.loginWithPopup();
    await handleStateChange();
  };

  const logout = async () => {
    state.auth0.logout({
      returnTo: window.location.origin,
    });
  };

  return {
    login,
    logout,
    initAuth,
  };
};

// and I use this on a button click event

AuthState.auth0.getTokenSilently().then(accessToken => {
   // AXIOS REQUEST
})
// PHP
// Auth0 SDK is 8.1.0

use Auth0\SDK\Auth0;
use Auth0\SDK\Utility\HttpResponse;
use Auth0\SDK\Token;

$env = (Dotenv\Dotenv::createImmutable(FCPATH))->load();
// I've checked that $env does contain correct .env values

$token = filter_var($_GET['token'] ?? null, FILTER_UNSAFE_RAW, FILTER_NULL_ON_FAILURE);
// Actual token I logged
eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9kZXYtd2kxeGRtbDcudXMuYXV0aDAuY29tLyJ9..V50FRJnBnpBnHJjA.e3PZuESoGaPCjp0kO9vlijGMIfhXWQHlbvsslWtbAvFAQ5hef9_PXLD_W282Cba9D6k-FAwhro9i3e5ukzXouGWYfoYHHQ5WQJ-vpLISrRANxFvNVPsCZSkg1sAIbL0Qk3Gir82ds1G919uEPc6vB3Y2qbARAd9nlMJBpLqWUq9VcIrzHtsJN7Q8j36vTCRXyu0f5-TeOr-dU3-gaIUvur37YQD0xICr4sENFktPU3s-uqCSCopVi6MoZMGvfYcVlO3nv1Sb2owGX_S_PSG7fug4Et-pMw1cVYgfNtLQf8XViI-l19sgXAf2eQShmLPvcdBdXVPA0g.S9vyktmK7rPoM_F3nUSEvg

$auth0 = new Auth0([
   'domain' => $env['AUTH0_DOMAIN'],
   'clientId' => $env['AUTH0_CLIENT_ID'],
   'clientSecret' => $env['AUTH0_CLIENT_SECRET'],
   'tokenAlgorithm' => 'RS256'
]);

// Exception thrown here with decode
$token = $auth0->decode($token, null, null, null, null, null, null, Token::TYPE_ID_TOKEN);

$token->verify();

$token->validate();

Is there and issue with auth0-spa-js when creating the token thats not compatible with Auth0 PHP SDK, or a configuration setting is not being passed that I need to add?在创建与 Auth0 PHP SDK 不兼容的令牌时,auth0-spa-js 是否存在问题,或者未传递我需要添加的配置设置? I've pretty much configured things as those two docs specify, double checking expected variables.我已经按照这两个文档的说明配置了很多东西,仔细检查了预期的变量。

Turns out I needed to add the audience parameter to the createAuth0Client, getTokenSilently(), and the PHP SDK decode method for my Auth0 Custom API. Everything validated.结果我需要将受众参数添加到 createAuth0Client、getTokenSilently() 和 PHP SDK 解码方法,用于我的 Auth0 自定义 API。一切都经过验证。

I must of missed something in the docs, or it seems that the audience parameter is more of a required than optional value.我一定是错过了文档中的某些内容,或者 audience 参数似乎比可选值更像是必需的。

Adding to Brian Barton's answer above , the GetTokenSilentlyOptions interface explains that the options should be passed as follows:添加到Brian Barton 上面的回答GetTokenSilentlyOptions接口解释说选项应该按如下方式传递:

// ✅ Like this!
const token = await this.$auth.getTokenSilently({
  authorizationParams: {
    audience: 'https://api.example.com/',
  },
})

// ❌ NOT like this (where I got stuck for a while)
const token = await this.$auth.getTokenSilently({
  audience: 'https://api.example.com/',
})

It wasn't immediately obvious to me that the additional outer object structure was required so I couldn't figure out why I couldn't get their solution to work.额外的外部 object 结构对我来说不是很明显,所以我无法弄清楚为什么我不能让他们的解决方案工作。

Additional Context附加上下文

This has NOTHING to do with what you have on the server side and everything to do with how your SPA retrieves your JWT tokens following the Authorization Code Flow with Proof Key for Code Exchange (PKCE) (which is the flow you should be using if you're accessing an API from an SPA).这与您在服务器端拥有的内容无关,也与您的 SPA 如何按照带有代码交换证明密钥的授权代码流 (PKCE)检索您的 884645589888 令牌有关(如果您'正在从 SPA 访问 API)。

I ended up finding this answer because when I failed to set the audience parameter correctly, Auth0 did NOT signal that there were any errors whatsoever.我最终找到了这个答案,因为当我未能正确设置audience参数时,Auth0 没有发出任何错误的信号。 It returned a "token" that NOT a well-formed JWT. In my case it consistently had four or five dots (periods) when there should have been exactly two.它返回了一个不是格式正确的 JWT 的“令牌”。在我的例子中,它始终有四个或五个点(句点),而本应恰好有两个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM