Please include the following information in your post:
Using React Auth0 SDK
API: Express, Cors Enabled, JWT
I can’t seem to get an Auth token for my Express API. I just started using Auth0. I’ll leave screenshots of my Auth0 config, and code snippets below:
// index.tsx
const onRedirectCallback = (appState:any) => {
// Use the router's history module to replace the url
history.replace(appState?.returnTo || window.location.pathname);
};
ReactDOM.render(
<React.StrictMode>
<Auth0Provider
domain="domain_would_go_here"
clientId="CLIENT_ID_WOULD_GO_HERE"
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
<App />
</Auth0Provider>,
</React.StrictMode>,
document.getElementById('root')
);
// App.tsx
import {
Router,
Switch,
Route,
Link
} from "react-router-dom";
import Login from './pages/Login'
import Logout from './pages/Logout'
import Messages from './pages/Messages'
export const history = createBrowserHistory();
function App() {
const { user, isAuthenticated, isLoading } = useAuth0();
if(isAuthenticated) {
console.log(user)
}
return (
<Router history={history}>
<Switch>
<Route path="/messages">
<Messages />
</Route>
<Route path="/login">
<Login />
</Route>
<Route path="/logout">
<Logout />
</Route>
<Route path="/" exact>
Home <Link to="/messages">Go to messages</Link><br />
<Link to="/login">Go to login</Link>
<br /><br />
Json: { JSON.stringify(user) }
</Route>
</Switch>
</Router>
);
}
// /pages/Messages.tsx
import React, {useEffect, useState} from 'react'
import { useAuth0 } from "@auth0/auth0-react";
const Messages = () => {
const {user, isAuthenticated, getAccessTokenSilently, loginWithRedirect} = useAuth0()
if(isAuthenticated){
getAccessTokenSilently({
audience: 'http://localhost:2081',
scope: 'read:message-list',
})
.then((res) => {
console.log(res)
// fetch('http://localhost:2081/api/list-messages', {
// headers: {
// Authorization: `Bearer ${res}`,
// },
// })
// .then((result) => {
// console.log(result)
// })
})
return(
<div>
Haha! Auth! Could be me!
</div>
)
} else {
// loginWithRedirect()
return (
<div>
<h1>Unauthorized</h1>
</div>
)
}
}
export default Messages
I really can’t figure out what the problem is. Anyone’s help is really appreciated
Thanks, Alexander