Data Provider with API cookies

I hav an API that creates cookies which are used for authentication purpose (they contains jwt acces and refresh tokens). How can I tell my dataProvider to use that cookie whenever a request is sent to the API? The API and Refine backend are on two different sub-domains, I have cors allowing cross-domain origin and credentials set to true.
K
kapa.ai147d ago
Hi @smilodon.x7. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To inform your data provider about the authentication credentials, you can send the authentication credentials with each request. After obtaining the authentication token, you can store it in cookies and send it with every request. In refine, you can use the dataProvider property of the <Refine> component to allow refine to communicate with the API. Here is an example of how to add a dataProvider to the refine component:
import { Refine } from "@refinedev/core";
import { authProvider, axiosInstance } from "./authProvider";
import { DataProvider } from "@refinedev/strapi-v4";

function App() {
return (
<Refine
dataProvider={DataProvider(API_URL + `/api`, axiosInstance)}
//...
/>
);
}

export default App;
import { Refine } from "@refinedev/core";
import { authProvider, axiosInstance } from "./authProvider";
import { DataProvider } from "@refinedev/strapi-v4";

function App() {
return (
<Refine
dataProvider={DataProvider(API_URL + `/api`, axiosInstance)}
//...
/>
);
}

export default App;
In the above code, axiosInstance is imported from the authProvider.ts file. This instance can be configured to include the authentication token in every request. Here is an example of how to create an authProvider:
import { AuthProvider } from "@pankod/refine-core";
import Cookies from "js-cookie";
import axios from "axios";
import { promises } from "dns";
const axiosInstance = axios.create();

export const TOKEN_KEY = "refine-auth";
export const authProvider: AuthProvider = {
login: async () => {
return Promise.resolve();
},
logout: () => {
localStorage.removeItem(TOKEN_KEY);
return Promise.resolve();
},
checkError: () => Promise.resolve(),
checkAuth: async () => {
let response = await axiosInstance.get("/api/auth")
if (!(response.status === 200)) {
const error = response.statusText;
return Promise.reject(error);
}
return Promise.resolve();
},
getPermissions: () => Promise.resolve(),
};
import { AuthProvider } from "@pankod/refine-core";
import Cookies from "js-cookie";
import axios from "axios";
import { promises } from "dns";
const axiosInstance = axios.create();

export const TOKEN_KEY = "refine-auth";
export const authProvider: AuthProvider = {
login: async () => {
return Promise.resolve();
},
logout: () => {
localStorage.removeItem(TOKEN_KEY);
return Promise.resolve();
},
checkError: () => Promise.resolve(),
checkAuth: async () => {
let response = await axiosInstance.get("/api/auth")
if (!(response.status === 200)) {
const error = response.statusText;
return Promise.reject(error);
}
return Promise.resolve();
},
getPermissions: () => Promise.resolve(),
};
In the above code, axiosInstance is used to send a GET request to "/api/auth". You can modify this code to include the authentication token in the headers of every request. For more information, you can refer to the refine's dataProvider prop component documentation (https://refine.dev/docs/api-reference/core/components/refine-config/#dataprovider) and the refine's guide on using authentication with data provider (https://refine.dev/docs/guides-concepts/authentication/#usage-with-data-provider-). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
K
kapa.ai147d ago
<@305970367405490186> kapa.ai is still learning and improving, please let us know how it did by reacting below
S
stormy-gold144d ago
Hello @smilodon.x7 as bot mentioned, you can pass a client to your data provider which reads cookies or you can swizzle and modify to read cookies and add to headers: https://refine.dev/docs/tutorial/understanding-dataprovider/swizzle/#what-is-swizzle
F
flat-fuchsia144d ago
Hello @batuhanw , thank you for your help 🙂 My API does not check the tokens within the headers but directly from the cookies created in the login route. Am I doing it the wrong way? Should I make my API check the header instead, then get the tokens from the cookies inside my authProvider and use them later with my dataProvider? I'm new to Refine and API development so please forgive me my beginner level 🙂
S
stormy-gold144d ago
I think you can use withCredentials option to also send cookies: https://bobbyhadz.com/blog/javascript-axios-set-cookies
Set Cookies when making an Axios request in JS and Node | bobbyhadz
You can set the withCredentials property to true in the configuration object to set cookies when making an Axios HTTP request.
F
flat-fuchsia144d ago
@batuhanw I swizzled the dataProvider and added the withCredentials in the axios.ts file like this : import { HttpError } from "@refinedev/core"; import axios from "axios"; const axiosInstance = axios.create({withCredentials: true}); axiosInstance.interceptors.response.use( (response) => { return response; }, (error) => { const customError: HttpError = { ...error, message: error.response?.data?.message, statusCode: error.response?.status, }; return Promise.reject(customError); } ); I tried with axios.defaults.withCredentials = true just in case but it did not work either
More Posts
How to get data from other tables via foreign keys (Supabase / Chakra UI tables)Hello, I have a question regarding the useTable hook, how do I set query options so I can do operatisearchParamshi, I m struggling to mimic refine's filters searchParams management. So i tried to convert my filteAdd custom menu item in ThemedSiderV2I want to customize my menu item using the Sider.tsx file that generated using Swizzle (ThemedSiderVHow to add a menu item in Sider with "create" action?I need a confirmation of the fact that resource in <Refine> will only create "list" menu item correcHow do you conventionally build a customHow do you conventionally build a custom menu on Sider (with CanAccess)? If using ITreeMenu default GraphQL order_by precedenceI need to be able to specify the order of my `order_by` fields sent via the GraphQL client to HasuraLoad data not from resource into a tableHow can you load data not from a resource into a table?Add a custom nested menu item with position definedexport const resources: IResourceItem[] = [ { name: "users", list: "/users", can useDrawerForm just refresh current page instead of redirecting to the list page?using Ant Design I have a useDrawerForm to submit a comment. The comment is on the show page of the Import pageHowdy, I want to create a page where I can - import a json file with a list of items - check if thosSyncwithlocationhow to achieve Syncwithlocation with useList like useTable, or if it's not supported, what's the cleHow to join populated row by countI am using useSimpleList, with the following config: meta: { populate: { jobRole: { Dashboardpage content not coming on the app, defined it in App.tsxDashboardPage only works with the legacy routing system. It will be removed in the next major releas'DashboardPage' is deprecated.ts(6385) index.d.ts(80, 8): The declaration was marked as deprecated hrefine project my layout folder in components seems not be connected whatever changes i make are noti swizzled in layoutsversion2 into my refine project but when i make changes into the sider, title fiam using latest @refinedev/core refineapp and iam not sure how can i edit the siderI created the refine project using npm create refine-app@latest and i wanted to edit sider and add mRefine Data Provider QueryHi Amazing folks @ Refine - Had a question about Refine Data Providers. I have created "named" data Making each list item in a DataGrid clickableWhen I go to a list page, it shows a list of items. I want to be able to click anywhere on a row to