API Key Authentication
The SecuritySchemeAPIKey
type is used for API key authentication, where the key can be placed in different locations
such as headers or query parameters.
See the OpenAPI API Key Authentication ๐ specification for more information.
type SecuritySchemeAPIKey = {
/** Where the secret should be placed. */
in: 'header' | 'query';
/** Name of the secret key. */
name: string;
/** Secret to be used for authentication. */
value: string;
/** Refresh interval in milliseconds. */
refreshInterval?: number;
};
- Location: Specifies that the secret is placed in the header or query parameters.
- Name: The name of the secret key.
- Value: The secret key to be used for authentication.
- 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={{
apiClientSecret: async () => {
const api = createAPIClient({
requestFn,
baseUrl: 'https://petstore3.swagger.io/api/v3',
});
const { secret } = await api.auth.getAPISecret({ parameters: undefined }, requestFn);
return {
in: 'header', // specify the location of the secret, either 'header' or 'query'
name: 'X-API-Secret',
value: secret,
// Specify the refresh interval in milliseconds if needed, or use Infinity to ask for the secret just once
refreshInterval: Infinity,
};
}
}}
>
{(secureRequestFn) => {
// When using `secureRequestFn`, all requests that require the `apiClientSecret` security scheme
// will automatically include the `X-API-Secret: <secret>` header.
// This ensures that these requests are authenticated using the API Key Authentication mechanism.
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;