Cookie Authentication
The SecuritySchemeCookie
type is used for cookie-based authentication, where the secret is placed in a cookie.
You can't specify the cookie name. The server must set the cookie.
See the OpenAPI Cookie Authentication ๐ specification for more information.
type SecuritySchemeCookie = {
/** Where the secret should be placed. */
in: 'cookie';
/** Refresh interval in milliseconds. */
refreshInterval?: number;
};
- Location: Specifies that the secret is placed in a cookie.
- Refresh Interval: (Optional) The interval (in milliseconds) at which the key should be refreshed.
Exampleโ
import { QraftSecureRequestFn } from '@openapi-qraft/react/Unstable_QraftSecureRequestFn';
import { requestFn } from '@openapi-qraft/react';
import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useMemo, createContext, type ReactNode } from 'react';
const App = ({ children }: { children: ReactNode }) => {
const queryClient = useMemo(() => new QueryClient(), []);
return (
<QueryClientProvider client={queryClient}>
<QraftSecureRequestFn
requestFn={requestFn}
securitySchemes={{
cookieAuth: async ({isRefreshing}) => {
const api = createAPIClient({
requestFn,
baseUrl: 'https://petstore3.swagger.io/api/v3',
});
await api.auth.cookieAuth(
isRefreshing
? { refresh: true }
: {
username: 'UNSECURE_TEST_USERNAME',
password: 'UNSECURE_TEST_PASSWORD',
},
);
return {
in: 'cookie',
refreshInterval: 3600_000, // 1 hour in milliseconds (optional)
};
},
}}
>
{(secureRequestFn) => {
// When using `secureRequestFn`, all requests that require the `cookieAuth` security scheme
// will ensure the necessary cookies for authentication are set by the server.
// The server is responsible for setting and updating the authentication cookie.
//
// The initial request will send the provided username and password to the server,
// which will respond by setting the authentication cookie. For subsequent requests,
// if the `isRefreshing` flag is true, a refresh request will be sent to update the cookie.
const api = createAPIClient({
queryClient,
requestFn: secureRequestFn,
baseUrl: 'https://petstore3.swagger.io/api/v3',
});
return (
<MyAPIContext.Provider value={api}>
{children}
</MyAPIContext.Provider>
)
}}
</QraftSecureRequestFn>
</QueryClientProvider>
);
};
const MyAPIContext = createContext<ReturnType<typeof createAPIClient>>(null!);
export default App;