rival-black
rival-black14mo ago

authorization token in refine api

refine api authorization token
2 Replies
kapa.ai
kapa.ai14mo ago
Hi @reactt. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- In refine, you can set the authorization token by using an auth provider. The auth provider is an object that contains methods to handle authentication and authorization in your app. You can create a custom auth provider and set the authorization token in the headers of your API calls using an HTTP client like axios. Here's an example of setting the authorization token using axios:
import { AuthBindings } from "@refinedev/core";
import axios, { AxiosRequestConfig } from "axios";

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use((request: AxiosRequestConfig) => {
// Retrieve the token from local storage
const token = JSON.parse(localStorage.getItem("auth"));
// Check if the header property exists
if (request.headers) {
// Set the Authorization header if it exists
request.headers["Authorization"] = `Bearer ${token}`;
} else {
// Create the headers property if it does not exist
request.headers = {
Authorization: `Bearer ${token}`,
};
}

return request;
});
import { AuthBindings } from "@refinedev/core";
import axios, { AxiosRequestConfig } from "axios";

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use((request: AxiosRequestConfig) => {
// Retrieve the token from local storage
const token = JSON.parse(localStorage.getItem("auth"));
// Check if the header property exists
if (request.headers) {
// Set the Authorization header if it exists
request.headers["Authorization"] = `Bearer ${token}`;
} else {
// Create the headers property if it does not exist
request.headers = {
Authorization: `Bearer ${token}`,
};
}

return request;
});
You can then pass the auth provider to the <Refine> component as a prop:
const App = () => {
const authProvider: AuthBindings = {
// ... other auth provider methods
};

return (
<Refine
authProvider={authProvider}
dataProvider={dataProvider(API_URL, axiosInstance)}
>
{/* ... */}
</Refine>
);
};
const App = () => {
const authProvider: AuthBindings = {
// ... other auth provider methods
};

return (
<Refine
authProvider={authProvider}
dataProvider={dataProvider(API_URL, axiosInstance)}
>
{/* ... */}
</Refine>
);
};
For more information on creating an auth provider from scratch, refer to the Create Auth Provider From Scratch tutorial (https://refine.dev/docs/tutorial/understanding-authprovider/create-authprovider/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai14mo ago
<@1048996483648725093> kapa.ai is still learning and improving, please let us how it did by reacting below