Using react front end with .net backend token is rejected

We’ve been trying to get this to work for a while now and I’m at wits end.

We have a react front end using the react SDK. In auth0 we have an application for Single Page Application that the front end can authenticate with and pull profile data from auth0. We have another application that is Machine to Machine that the backend is connected with.

We can use insomnia to get a token and access the backend however the fronted is rejected 401

Here is the relevant react code

import { createContext, useState, useEffect } from 'react';
import { useAuth0, Auth0Provider } from '@auth0/auth0-react';

export const AuthContext = createContext();

export const TokenProvider = ({ children }) => {
    const [token, setToken] = useState(null);
    const { isAuthenticated, getAccessTokenSilently } = useAuth0();

    useEffect(() => {
        if (isAuthenticated) {
            getAccessTokenSilently()
                .then(token => setToken(token))
                .catch(err => console.log('Error fetching token:', err));
        }
    }, [isAuthenticated, getAccessTokenSilently]);

    return (
        <AuthContext.Provider value={{ token }}>
            {children}
        </AuthContext.Provider>
    );
}

export const AuthProvider = ({ children, domain, clientId, authorizationParams }) => {
    return (
        <Auth0Provider
            domain={domain}
            clientId={clientId}
            authorizationParams={authorizationParams}
        >
            <TokenProvider>
                {children}
            </TokenProvider>
        </Auth0Provider>
    );
}

And the .net code

            var domain = $"https://{Configuration["Auth0:Domain"]}/";
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = domain;
                    options.Audience = Configuration["Auth0:Audience"];
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("read:messages", policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
            });

Hi @bjones,

Welcome to the Auth0 Community!

There should be an error message telling a bit more about why the token was not accepted. Additionally, can you please post an example token payload (sensitive data excluded). You can decode it using JWT.io.

Thank you!

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