Why does my app stop working when I add middleware to check my JWT token?

Hello!

I just trying to get that hang of Auth0 and I seem to be running into a little issue when it comes to JWT verification.

The app is simple so far. When a user logs in, I want to create a user in my database and I want to make sure that user is authenticated before this happens. I am running vite with express as the backend and everything seems to work fine without the JWT Check.

I am using express-oauth2-jwt-bearer package to get the JWT middleware as this is what it states in the quickstart for the auth0 API. It gives me the error of 401 with unathorized and I am just wondering if there is anyone who can help me as I am wracking my brain and even building something bare bones and still get the same thing.

Middleware that I am using

export const jwtCheck = auth({
  issuer: process.env.AUTH0_ISSUER_BASE_URL,
  audience: process.env.AUTH0_AUDIENCE,
  secret: process.env.AUTH0_SECRET,
  tokenSigningAlg: "HS256",
});

I did do some digging and from what I understand in that package, it gets the access codes from header and query of the request but my query param comes back empty when I console log it.

Auth0 Provider

export default function Auth0ProviderWithNavigate({ children }: Props) {
  const navigate = useNavigate();
  const domain = secret
  const clientId = secret
  const redirectUrl =  secret
  const audience = secret

  if (!domain || !clientId || !redirectUrl || !audience) {
    throw new Error("unable to initialise auth");
  }

  const onRedirectCallback = () => {
    navigate("/auth-callback");
  };

  return (
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      authorizationParams={{
        redirect_uri: redirectUrl,
        audience,
      }}
      onRedirectCallback={onRedirectCallback}
    >
      {children}
    </Auth0Provider>
  );
}```

Hook for API call with react query

export const useCreateMyUser = () => {
const { getAccessTokenSilently } = useAuth0();

const createMyUserRequest = async (user: CreateUserRequest) => {
const accessToken = await getAccessTokenSilently({
authorizationParams: { audience: API_BASE_AUDIENCE },
});
const response = await fetch(${API_BASE_URL}/api/my/user, {
method: “POST”,
headers: {
authorzation: Bearer ${accessToken},
“Content-Type”: “application/json”,
},
body: JSON.stringify(user),
});

if (!response.ok) {
  throw new Error("Failed to create user");
}

};

const {
mutateAsync: createUser,
isLoading,
isError,
isSuccess,
} = useMutation(createMyUserRequest);

return { createUser, isLoading, isError, isSuccess };
};

At this point, i just want to understand why this is happening.

Any help would be greatly appriciated.

Thanks,
Jack

I don’t really know what happened with the code, but i am just adding it again.

export const useCreateMyUser = () => {
  const { getAccessTokenSilently } = useAuth0();

  const createMyUserRequest = async (user: CreateUserRequest) => {
    const accessToken = await getAccessTokenSilently({
      authorizationParams: { audience: API_BASE_AUDIENCE },
    });
    const response = await fetch(`${API_BASE_URL}/api/my/user`, {
      method: "POST",
      headers: {
        authorzation: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(user),
    });

    if (!response.ok) {
      throw new Error("Failed to create user");
    }
  };

  const {
    mutateAsync: createUser,
    isLoading,
    isError,
    isSuccess,
  } = useMutation(createMyUserRequest);

  return { createUser, isLoading, isError, isSuccess };
};

Hey there @jack.morrell79 welcome to the community!

Are you successfully getting a user’s access token on login? Are you able to decode it at jwt.io?

Hello @tyf,

Thanks for coming back to me about this. I have just run the program again and I defiantly get back a token that comes back with the following params:

  • access_token
  • id_token
  • scope
  • expires_in
  • token_type

When putting in the access token into https://jwt.io/, it seemed to be invalid at first but once i changed the signiture to HS256 which is was it is in my middleware and what it is in the settings for Auth0, it says signature verified.

I did as well test the access code from the header of my request being sent from my frontend and it is exactly the same and gives me signature verified.

I look forward to hearing from you.
Jack

1 Like

No problem, happy to help where I can!

A couple things:

  • Is there a specific reason you are looking to use HS256 as opposed to RS256 signing algorithm? RS256 in generally preferred.

  • Is your API set to use HS256 in settings? You should be able to check by navigating your API registered in Auth0 and scrolling down to Token Settings.

Some more on signing algorithms here:

@tyf Hello,

Thanks for getting back to me.

There was no real reason why I was looking to use HS256 as I was merely testing to see if anything else what change with the JWT token.

I have just updated back to RS256 and still get the same error of unathorized.

Both my API is set to RS258 now as I deleted and created another to make sure they were the same. I even used the quick start and it still gave me the same error.

Thanks for the help with with this.

Thanks for clarifying!

What does an example access token look like now when decoded at jwt.io? Feel free to share the results here and just obfuscate any sensitive data.

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.