简体   繁体   中英

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 . 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.

Server side I get an exception "The JWT string must contain two dots" after setting up steps from https://github.com/auth0/auth0-PHP . I've installed the requirements, guzzle and dotenv, etc. Currently on 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? 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.

I must of missed something in the docs, or it seems that the audience parameter is more of a required than optional value.

Adding to Brian Barton's answer above , the GetTokenSilentlyOptions interface explains that the options should be passed as follows:

// ✅ 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.

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).

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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