Skip to main content
Version: 1.x

Bearer Token Authentication

The SecuritySchemeBearer type supports bearer token authentication, commonly used with JWT tokens. It can either be a simple string representing the JWT token or an object with additional metadata if another token format is used.

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

type SecuritySchemeBearer =
| string /** JWT Bearer token **/
| {
/** Refresh interval in milliseconds. */
refreshInterval: number;
/** Token to be used for authentication. */
token: string;
};
  • String: A simple JWT Bearer token string.
    • The JWT must include the exp (expiration time) and iat (issued at) fields.
    • QraftSecureRequestFn will automatically refresh the token if it expires.
    • If the exp and iat fields are not present, an object token format must be used; otherwise, an error will be thrown.
  • Object: An object containing:
    • refreshInterval: The interval (in milliseconds) at which the token should be refreshed.
    • token: The JWT token to be used for authentication.

Examplesโ€‹

When providing a simple JWT Bearer token string, the token will be used as is. QraftSecureRequestFn will refresh the token if it expires based on the exp (expiration time) and iat (issued at) fields.

In this example, the clientToken security scheme handler is used to obtain and refresh the JWT Bearer token:

import { ReactNode } from 'react';
import { requestFn, QraftContext } from '@openapi-qraft/react';
import { QraftSecureRequestFn } from '@openapi-qraft/react/Unstable_QraftSecureRequestFn';
import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI

const qraft = createAPIClient();

const App = ({ children }: { children: ReactNode }) => {
return (
<QraftSecureRequestFn
requestFn={requestFn}
securitySchemes={{
clientToken: async ({ isRefreshing }) => {
if (!isRefreshing) {
const { access_token } = await qraft.auth.obtainToken({
body: {
grant_type: 'client_credentials', // specify `body` or `parameters` if needed
},
}, requestFn);

// If token is JWT Bearer, return the token string
// The token will be used in the `Authorization: Bearer <token>` header
return access_token;
}

const { access_token } = await qraft.auth.refreshToken({
body: {
grant_type: 'client_credentials', // specify `body` or `parameters` if needed
},
}, requestFn);

return access_token;
}
}}
>
{(secureRequestFn) => (
// When using `secureRequestFn`, all requests that require the `clientToken` security scheme
// will automatically include the `Authorization: Bearer <token>` header.
// This ensures that these requests are authenticated with the provided JWT token.
<QraftContext.Provider value={{ requestFn: secureRequestFn }}>
{children}
</QraftContext.Provider>
)}
</QraftSecureRequestFn>
);
};

export default App;