Hello there. I am new here trying to use Auth0’s authorization capabilities. Im just trying to get my head around all these complexities. Any help would be appreciated! Thank you.
- I was able create a simple universal login with my SPA using react typescript.
- I was following this tutorial to set up django api authentication . Creating a new API with audience https://webapp/api and permission read:messages https://auth0.com/docs/quickstart/backend/django/01-authorization
Here below is my whole SPA. What Im trying to do is access the api/public api/private from the tutorial but I couldnt figure it out how to obtain the access token. I’ve tried await getAccessTokenSilently({audience: ‘https://webapp/api’, scope: 'read:messages}) but it would say consent required. I tried just calling getAccessTokenSilently but i got a 401 unauthorized error. Any ideas? Thank you!
const User = () => {
const { user, getAccessTokenSilently, logout } = useAuth0();
useEffect(() => {
const getUserMetadata = async () => {
try {
const accessToken = await getAccessTokenSilently();
const axiosAPI = axios.create({
baseURL: 'http://localhost:8000',
timeout: 120000,
headers: {
Authorization: accessToken ? `Bearer ${accessToken}` : null,
},
});
const response = await axiosAPI.get(`http://localhost:8000/api/public`);
console.log("response ", response);
} catch (e) {
console.log("error ", e);
}
};
getUserMetadata();
}, [getAccessTokenSilently, user?.sub]);
return (
<div>
<img src={user?.picture} alt={user?.name} />
<h2>{user?.name}</h2>
<p>{user?.email}</p>
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log Out
</button>
</div>
);
};
const App = (): ReactElement => {
const { loginWithRedirect, isAuthenticated, isLoading } = useAuth0();
if (isLoading) {
return <div>Loading ...</div>;
}
return isAuthenticated ? (
<User />
) : (
<button onClick={() => loginWithRedirect()}>Log In</button>
);
};