Skip to main content
Version: 2.x ๐Ÿšง

Basic Authentication

The SecuritySchemeBasic type is used for basic authentication, where credentials are required.

See the OpenAPI Basic Authentication ๐Ÿ”— specification for more information.

type SecuritySchemeBasic = {
/** Credentials to be used for authentication. */
credentials: string;

/** Refresh interval in milliseconds. */
refreshInterval: number;
}
  • Credentials: A string representing the username and password encoded in Base64.
  • Refresh Interval: 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={{
basicAuth: () => {
// Function to prompt user for basic authentication credentials
const username = prompt('Enter your username:');
const password = prompt('Enter your password:');
return {
credentials: btoa(`${username}:${password}`),
// Ask for credentials just once or specify the refresh interval in milliseconds.
refreshInterval: Infinity,
};
}
}}
>
{(secureRequestFn) => {
const api = createAPIClient({
queryClient,
requestFn: secureRequestFn,
baseUrl: 'https://petstore3.swagger.io/api/v3',
});

// When using `secureRequestFn`, the first request that requires the `basicAuth` security scheme
// will prompt the user for their username and password. These credentials are then encoded in
// Base64 format and included in the `Authorization: Basic <credentials>` header for subsequent requests.
// This ensures that the requests are authenticated using Basic Authentication.
// The credentials will be asked just once, and all following requests will reuse the entered credentials.
return (
<MyAPIContext.Provider value={api}>
{children}
</MyAPIContext.Provider>
)
}}
</QraftSecureRequestFn>
</QueryClientProvider>
);
};

const MyAPIContext = createContext<ReturnType<typeof createAPIClient>>(null!);

export default App;