(auth0-react) What is the proper way to get the access token if a user is authenticated?

So I am trying to do something similar to this but trying to call an API with the access token like this

export function CBusAppBar() {
    const [anchorEl, setAnchorEl] = useState(null);
    const {
        isAuthenticated,
        isLoading,
        user,
        getAccessTokenSilently,
        getAccessTokenWithPopup
    } = useAuth0();
    const getAccessToken = async () => {
        try {
            await getAccessTokenSilently();
        } catch (e) {
            if (e.error === 'login_required') {
                // if silent auth fails, fall back to popup
                await getAccessTokenWithPopup();
            } else {
                console.error(e);
            }
        }
    };
    const checkAuthorities = async () => {
        const token = await getAccessToken();
        const response = await fetch("/user/authorities",{
            headers: {
                Authorization: `Bearer ${token}`
            }
        })
        const authorities = await response.json();
        console.log(authorities);
    }
    useEffect(() => {
        checkAuthorities();
    }, []);

    const handleUserDropdown = (event) => {
        setAnchorEl(event.currentTarget);
    };
    return (
        <AppBar position="static" elevation={0}>
            <Toolbar sx={{
                alignItems: 'stretch',
            }}>
                {isAuthenticated ? <Dropdown/> : <div/>}
                ...
        </AppBar>
    )
}

But when I try this way the access token is undefined. What am I missing? Should I be using an AuthGaurd or something instead? I do see the http call being made but the header reflects the undefined.

It looks like you are not returning anything in the getAccessToken function, so it is expected to return undefined. Please try:

const getAccessToken = async () => {
        let token;
        try {
            token = await getAccessTokenSilently();
        } catch (e) {
            if (e.error === 'login_required') {
                // if silent auth fails, fall back to popup
                token = await getAccessTokenWithPopup();
            } else {
                console.error(e);
            }
        }
       return token;
    };
1 Like