Gathering detailed insights and metrics for react-oidc-context
Gathering detailed insights and metrics for react-oidc-context
Gathering detailed insights and metrics for react-oidc-context
Gathering detailed insights and metrics for react-oidc-context
@axa-fr/react-oidc-context
OpenID Connect & OAuth authentication using react
@carp-dk/authentication-react
A wrapper for [oidc-client-ts](https://github.com/authts/oidc-client-ts) and [react-oidc-context](https://github.com/authts/react-oidc-context) for shared authentication config and logic across CARP react projects
@aws-sdk/client-sso-oidc
AWS SDK for JavaScript Sso Oidc Client for Node.js, Browser and React Native
oidc-spa
Openidconnect client for Single Page Applications
Lightweight auth library based on oidc-client-ts for React single page applications (SPA). Support for hooks and higher-order components (HOC).
npm install react-oidc-context
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
721 Stars
1,599 Commits
68 Forks
11 Watching
9 Branches
21 Contributors
Updated on 27 Nov 2024
TypeScript (95.25%)
JavaScript (4.05%)
HTML (0.7%)
Cumulative downloads
Total Downloads
Last day
-4.5%
23,102
Compared to previous day
Last week
2.1%
119,798
Compared to previous week
Last month
11.3%
515,653
Compared to previous month
Last year
107.8%
4,994,988
Compared to previous year
2
26
Lightweight auth library using the oidc-client-ts library for React single page applications (SPA). Support for hooks and higher-order components (HOC).
This library implements an auth context provider by making use of the
oidc-client-ts
library. Its configuration is tight coupled to that library.
The
User
and
UserManager
is hold in this context, which is accessible from the
React application. Additionally it intercepts the auth redirects by looking at
the query/fragment parameters and acts accordingly. You still need to setup a
redirect uri, which must point to your application, but you do not need to
create that route.
To renew the access token, the
automatic silent renew
feature of oidc-client-ts
can be used.
Using npm
1npm install oidc-client-ts react-oidc-context --save
Using yarn
1yarn add oidc-client-ts react-oidc-context
Configure the library by wrapping your application in AuthProvider
:
1// src/index.jsx 2import React from "react"; 3import ReactDOM from "react-dom"; 4import { AuthProvider } from "react-oidc-context"; 5import App from "./App"; 6 7const oidcConfig = { 8 authority: "<your authority>", 9 client_id: "<your client id>", 10 redirect_uri: "<your redirect uri>", 11 // ... 12}; 13 14ReactDOM.render( 15 <AuthProvider {...oidcConfig}> 16 <App /> 17 </AuthProvider>, 18 document.getElementById("app") 19);
Use the useAuth
hook in your components to access authentication state
(isLoading
, isAuthenticated
and user
) and authentication methods
(signinRedirect
, removeUser
and signOutRedirect
):
1// src/App.jsx 2import React from "react"; 3import { useAuth } from "react-oidc-context"; 4 5function App() { 6 const auth = useAuth(); 7 8 switch (auth.activeNavigator) { 9 case "signinSilent": 10 return <div>Signing you in...</div>; 11 case "signoutRedirect": 12 return <div>Signing you out...</div>; 13 } 14 15 if (auth.isLoading) { 16 return <div>Loading...</div>; 17 } 18 19 if (auth.error) { 20 return <div>Oops... {auth.error.message}</div>; 21 } 22 23 if (auth.isAuthenticated) { 24 return ( 25 <div> 26 Hello {auth.user?.profile.sub}{" "} 27 <button onClick={() => void auth.removeUser()}>Log out</button> 28 </div> 29 ); 30 } 31 32 return <button onClick={() => void auth.signinRedirect()}>Log in</button>; 33} 34 35export default App;
You must provide an implementation of onSigninCallback
to oidcConfig
to remove the payload from the URL upon successful login. Otherwise if you refresh the page and the payload is still there, signinSilent
- which handles renewing your token - won't work.
A working implementation is already in the code here.
Use the withAuth
higher-order component to add the auth
property to class
components:
1// src/Profile.jsx 2import React from "react"; 3import { withAuth } from "react-oidc-context"; 4 5class Profile extends React.Component { 6 render() { 7 // `this.props.auth` has all the same properties as the `useAuth` hook 8 const auth = this.props.auth; 9 return <div>Hello {auth.user?.profile.sub}</div>; 10 } 11} 12 13export default withAuth(Profile);
As a child of AuthProvider
with a user containing an access token:
1// src/Posts.jsx 2import React from "react"; 3import { useAuth } from "react-oidc-context"; 4 5const Posts = () => { 6 const auth = useAuth(); 7 const [posts, setPosts] = React.useState(Array); 8 9 React.useEffect(() => { 10 (async () => { 11 try { 12 const token = auth.user?.access_token; 13 const response = await fetch("https://api.example.com/posts", { 14 headers: { 15 Authorization: `Bearer ${token}`, 16 }, 17 }); 18 setPosts(await response.json()); 19 } catch (e) { 20 console.error(e); 21 } 22 })(); 23 }, [auth]); 24 25 if (!posts.length) { 26 return <div>Loading...</div>; 27 } 28 29 return ( 30 <ul> 31 {posts.map((post, index) => { 32 return <li key={index}>{post}</li>; 33 })} 34 </ul> 35 ); 36}; 37 38export default Posts;
As not a child of AuthProvider
(e.g. redux slice) when using local storage
(WebStorageStateStore
) for the user containing an access token:
1// src/slice.js 2import { User } from "oidc-client-ts" 3 4function getUser() { 5 const oidcStorage = localStorage.getItem(`oidc.user:<your authority>:<your client id>`) 6 if (!oidcStorage) { 7 return null; 8 } 9 10 return User.fromStorageString(oidcStorage); 11} 12 13export const getPosts = createAsyncThunk( 14 "store/getPosts", 15 async () => { 16 const user = getUser(); 17 const token = user?.access_token; 18 return fetch("https://api.example.com/posts", { 19 headers: { 20 Authorization: `Bearer ${token}`, 21 }, 22 }); 23 }, 24 // ... 25)
Secure a route component by using the withAuthenticationRequired
higher-order component. If a user attempts
to access this route without authentication, they will be redirected to the login page.
1import React from 'react'; 2import { withAuthenticationRequired } from "react-oidc-context"; 3 4const PrivateRoute = () => (<div>Private</div>); 5 6export default withAuthenticationRequired(PrivateRoute, { 7 OnRedirecting: () => (<div>Redirecting to the login page...</div>) 8});
The underlying UserManagerEvents
instance can be imperatively managed with the useAuth
hook.
1// src/App.jsx 2import React from "react"; 3import { useAuth } from "react-oidc-context"; 4 5function App() { 6 const auth = useAuth(); 7 8 React.useEffect(() => { 9 // the `return` is important - addAccessTokenExpiring() returns a cleanup function 10 return auth.events.addAccessTokenExpiring(() => { 11 if (alert("You're about to be signed out due to inactivity. Press continue to stay signed in.")) { 12 auth.signinSilent(); 13 } 14 }) 15 }, [auth.events, auth.signinSilent]); 16 17 return <button onClick={() => void auth.signinRedirect()}>Log in</button>; 18} 19 20export default App;
Automatically sign-in and silently reestablish your previous session, if you close the tab and reopen the application.
1// index.jsx
2const oidcConfig: AuthProviderProps = {
3 ...
4 userStore: new WebStorageStateStore({ store: window.localStorage }),
5};
1// src/App.jsx 2import React from "react"; 3import { useAuth, hasAuthParams } from "react-oidc-context"; 4 5function App() { 6 const auth = useAuth(); 7 const [hasTriedSignin, setHasTriedSignin] = React.useState(false); 8 9 // automatically sign-in 10 React.useEffect(() => { 11 if (!hasAuthParams() && 12 !auth.isAuthenticated && !auth.activeNavigator && !auth.isLoading && 13 !hasTriedSignin 14 ) { 15 auth.signinRedirect(); 16 setHasTriedSignin(true); 17 } 18 }, [auth, hasTriedSignin]); 19 20 if (auth.isLoading) { 21 return <div>Signing you in/out...</div>; 22 } 23 24 if (!auth.isAuthenticated) { 25 return <div>Unable to log in</div>; 26 } 27 28 return <button onClick={() => void auth.removeUser()}>Log out</button>; 29} 30 31export default App;
We appreciate feedback and contribution to this repo!
This library is inspired by oidc-react, which lacks error handling and auth0-react, which is focused on auth0.
This project is licensed under the MIT license. See the LICENSE file for more info.
No vulnerabilities found.
No security vulnerabilities found.