React hooks implementing the Authorization Code Grant Flow with PKCE.
npm install @emdgroup/react-auth- LoginOptions
- ProviderOptions
- UserContext
- UserInfo
- UserSession
▸ UserContextProvider(__namedParameters): JSX.Element
This library implements the Authorization Code Grant Flow with PKCE.
``tsx
import { UserContextProvider } from '@emdgroup/react-auth';
function App(): JSX.Element {
return (
);
}
function Content(): JSX.Element {
const { info } = useUser();
return
{info.email}
;#### Parameters
| Name | Type |
| :------ | :------ |
|
__namedParameters | ProviderOptions |#### Returns
JSX.Element___
$3
▸ getAccessToken(
__namedParameters): Promise<string\>Return a valid access token for the current user. If the stored session is expired and a refresh token
is available, the function attempts to refresh the session automatically. If the user is not authenticated,
it rejects with an error. On refresh failure, the stored session is cleared.
`ts
const token = await getAccessToken({
idpHost: 'login.emddigital.com',
clientId: 'my-client-id',
});
fetch('/api/resource', { headers: { Authorization: Bearer ${token} } });
`
ThrowsError when the user is not authenticated (no stored session).
#### Parameters
| Name | Type |
| :------ | :------ |
|
__namedParameters | Object |
| __namedParameters.clientId | string |
| __namedParameters.idpHost | string |
| __namedParameters.signal? | AbortSignal |#### Returns
Promise<string\>Promise that resolves to a bearer access token string.
___
$3
▸ refreshSession(
__namedParameters): Promise<UserSession\>Exchange a refresh token for a new session using the OAuth 2.0 refresh_token grant.
This function deduplicates concurrent calls: multiple invocations while a refresh is in progress
will share the same promise. On success, it updates localStorage with the new session and emits
a storage event to synchronize other tabs/components.
`ts
const session = await refreshSession({
idpHost: 'login.emddigital.com',
clientId: 'my-client-id',
refreshToken,
});
// session.accessToken, session.expires, ...
`#### Parameters
| Name | Type |
| :------ | :------ |
|
__namedParameters | Object |
| __namedParameters.clientId | string |
| __namedParameters.idpHost | string |
| __namedParameters.refreshToken | string |
| __namedParameters.signal? | AbortSignal |#### Returns
Promise<UserSession\>Promise that resolves to the renewed UserSession.
___
$3
▸ useUser():
UserContextReturns the user context previously established with
UserContextProvider.`ts
const { info, session, login, logout, authHeader } = useUser();useEffect(() => {
if (!session) return; // user is not logged in
fetch('/api/pet', { headers: authHeader }).then(...);
}, [session, authHeader]);
`#### Returns
UserContext
UserContext
The user context object is returned by the
useUser hook.Properties
$3
•
Optional authHeader: ObjectConvenience header object containing the
Authorization header value set to the access token.#### Index signature
▪ [key:
string]: string___
$3
•
Optional info: UserInfoProvides the
UserInfo object if the user is authenticated.___
$3
•
Optional login: (opts?: LoginOptions) => void#### Type declaration
▸ (
opts?): voidFunction to initiate the login flow.
##### Parameters
| Name | Type |
| :------ | :------ |
|
opts? | LoginOptions |##### Returns
void___
$3
•
Optional loginUrl: stringSet to the URL that the user is redirected to initiate the authorization flow. Useful when you need to start the login flow in a separate window or tab. Use in combination with
login({ refresh: false }).___
$3
•
Optional logout: () => void#### Type declaration
▸ ():
voidFunction to log the user out.
##### Returns
void___
$3
•
Optional session: UserSessionProvides the
UserSession object if the user is authenticated.
ProviderOptions
Properties
$3
•
Optional acrValues: stringRequest a type of multi-factor authentication. Currently,
mfa is the only supported value.___
$3
•
Optional additionalParameters: stringAdditional query parameters, such as
state=xyz.___
$3
•
Optional autoLogin: booleanWhen enabled, the user will automatically be logged in when the page is loaded. Defaults to
false.___
$3
• clientId:
stringClient ID as provided by the IdP.
___
$3
•
Optional domainHint: stringDomain name to directly forward a user to the login page for a certain auth domain.
___
$3
•
Optional idpHost: stringOverwrite the IdP host, defaults to
login.emddigital.com.___
$3
•
Optional prompt: "login"Whether the authorization server prompts the user for re-authentication.
___
$3
•
Optional redirectUri: stringOverwrite the redirect URI, defaults to the current hostname +
/auth.___
$3
•
Optional refreshSession: booleanPersist and use the refreshToken to renew an expired accessToken. Defaults to
false.___
$3
•
Optional userInfoEndpoint: stringOverwrite the userinfo endpoint, defaults to
/oauth2/userinfo.
LoginOptions
Object representing the options for the login function of the UserContext.
Properties
$3
•
Optional entrypoint: stringEntrypoint to redirect the user to after successful authentication. Defaults to the URL that the user initially visited.
___
$3
•
Optional redirect: booleanAutomatically redirect the user to the login URL and to the entrypoint after successful authentication. Disabling this will disable all redirects. Defaults to
false.
UserSession
Object containing the OIDC tokens and expiration time.
Properties
$3
• accessToken:
stringOAuth access token provided by the IDP
___
$3
• expires:
numberEpoch time in seconds when the access token expires
___
$3
•
Optional idToken: stringOAuth ID token provided by the IDP
___
$3
•
Optional refreshToken: stringOAuth refresh token provided by the IDP
UserInfo
Object representing the user details as provided by the IdP
userInfo endpoint.Hierarchy
-
Record<string, unknown\> ↳
UserInfoProperties
$3
• email:
stringEmail address
___
$3
•
Optional familyName: stringFamily name of provided
___
$3
•
Optional givenName: stringGiven name of provided
___
$3
• sub:
string`Subject identifier