{"id":14957161,"url":"https://github.com/authts/react-oidc-context","last_synced_at":"2025-05-13T23:08:26.205Z","repository":{"id":37391029,"uuid":"364597345","full_name":"authts/react-oidc-context","owner":"authts","description":"Lightweight auth library based on oidc-client-ts for React single page applications (SPA). Support for hooks and higher-order components (HOC).","archived":false,"fork":false,"pushed_at":"2025-05-07T07:45:10.000Z","size":6062,"stargazers_count":838,"open_issues_count":76,"forks_count":80,"subscribers_count":11,"default_branch":"main","last_synced_at":"2025-05-07T08:41:06.395Z","etag":null,"topics":["hooks","oidc","oidc-client","react","reactjs","spa","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/authts.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-05-05T14:06:29.000Z","updated_at":"2025-05-07T07:45:13.000Z","dependencies_parsed_at":"2023-07-23T02:33:57.861Z","dependency_job_id":"825184e1-fcc7-4006-bbdc-0541094b91b1","html_url":"https://github.com/authts/react-oidc-context","commit_stats":{"total_commits":862,"total_committers":21,"mean_commits":41.04761904761905,"dds":"0.21809744779582363","last_synced_commit":"cf05cf6d5b5c19b803b611a325b770877adec09f"},"previous_names":["pamapa/react-oidc-context"],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/authts%2Freact-oidc-context","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/authts%2Freact-oidc-context/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/authts%2Freact-oidc-context/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/authts%2Freact-oidc-context/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/authts","download_url":"https://codeload.github.com/authts/react-oidc-context/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253675170,"owners_count":21945909,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hooks","oidc","oidc-client","react","reactjs","spa","typescript"],"created_at":"2024-09-24T13:14:16.018Z","updated_at":"2025-05-13T23:08:21.189Z","avatar_url":"https://github.com/authts.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# react-oidc-context\n\n[![Stable Release](https://img.shields.io/npm/v/react-oidc-context.svg)](https://npm.im/react-oidc-context)\n[![CI](https://github.com/authts/react-oidc-context/actions/workflows/ci.yml/badge.svg)](https://github.com/authts/react-oidc-context/actions/workflows/ci.yml)\n[![Codecov](https://img.shields.io/codecov/c/github/authts/react-oidc-context)](https://app.codecov.io/gh/authts/react-oidc-context)\n\nLightweight auth library using the\n[oidc-client-ts](https://github.com/authts/oidc-client-ts) library for React\nsingle page applications (SPA). Support for\n[hooks](https://reactjs.org/docs/hooks-intro.html) and\n[higher-order components (HOC)](https://reactjs.org/docs/higher-order-components.html).\n\n## Table of Contents\n\n- [Documentation](#documentation)\n- [Installation](#installation)\n- [Getting Started](#getting-started)\n- [Contributing](#contributing)\n- [Influences](#influences)\n- [License](#license)\n\n## Documentation\n\nThis library implements an auth context provider by making use of the\n`oidc-client-ts` library. Its configuration is tight coupled to that library.\n\n- [oidc-client-ts](https://github.com/authts/oidc-client-ts)\n\nThe\n[`User`](https://authts.github.io/oidc-client-ts/classes/User.html)\nand\n[`UserManager`](https://authts.github.io/oidc-client-ts/classes/UserManager.html)\nis hold in this context, which is accessible from the\nReact application. Additionally it intercepts the auth redirects by looking at\nthe query/fragment parameters and acts accordingly. You still need to setup a\nredirect uri, which must point to your application, but you do not need to\ncreate that route.\n\nTo renew the access token, the\n[automatic silent renew](https://authts.github.io/oidc-client-ts/interfaces/UserManagerSettings.html#automaticSilentRenew)\nfeature of `oidc-client-ts` can be used.\n\n## Installation\n\nUsing [npm](https://npmjs.org/)\n\n```bash\nnpm install oidc-client-ts react-oidc-context --save\n```\n\nUsing [yarn](https://yarnpkg.com/)\n\n```bash\nyarn add oidc-client-ts react-oidc-context\n```\n\n## Getting Started\n\nConfigure the library by wrapping your application in `AuthProvider`:\n\n```jsx\n// src/index.jsx\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { AuthProvider } from \"react-oidc-context\";\nimport App from \"./App\";\n\nconst oidcConfig = {\n  authority: \"\u003cyour authority\u003e\",\n  client_id: \"\u003cyour client id\u003e\",\n  redirect_uri: \"\u003cyour redirect uri\u003e\",\n  // ...\n};\n\nReactDOM.render(\n  \u003cAuthProvider {...oidcConfig}\u003e\n    \u003cApp /\u003e\n  \u003c/AuthProvider\u003e,\n  document.getElementById(\"app\")\n);\n```\n\nUse the `useAuth` hook in your components to access authentication state\n(`isLoading`, `isAuthenticated` and `user`) and authentication methods\n(`signinRedirect`, `removeUser` and `signOutRedirect`):\n\n```jsx\n// src/App.jsx\nimport React from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\nfunction App() {\n    const auth = useAuth();\n\n    switch (auth.activeNavigator) {\n        case \"signinSilent\":\n            return \u003cdiv\u003eSigning you in...\u003c/div\u003e;\n        case \"signoutRedirect\":\n            return \u003cdiv\u003eSigning you out...\u003c/div\u003e;\n    }\n\n    if (auth.isLoading) {\n        return \u003cdiv\u003eLoading...\u003c/div\u003e;\n    }\n\n    if (auth.error) {\n        return \u003cdiv\u003eOops... {auth.error.kind} caused {auth.error.message}\u003c/div\u003e;\n    }\n\n    if (auth.isAuthenticated) {\n        return (\n        \u003cdiv\u003e\n            Hello {auth.user?.profile.sub}{\" \"}\n            \u003cbutton onClick={() =\u003e void auth.removeUser()}\u003eLog out\u003c/button\u003e\n        \u003c/div\u003e\n        );\n    }\n\n    return \u003cbutton onClick={() =\u003e void auth.signinRedirect()}\u003eLog in\u003c/button\u003e;\n}\n\nexport default App;\n```\n\nYou **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.\n\nA working implementation is already in the code [here](https://github.com/authts/react-oidc-context/blob/f175dcba6ab09871b027d6a2f2224a17712b67c5/src/AuthProvider.tsx#L20-L30).\n\n\n### Use with a Class Component\n\nUse the `withAuth` higher-order component to add the `auth` property to class\ncomponents:\n\n```jsx\n// src/Profile.jsx\nimport React from \"react\";\nimport { withAuth } from \"react-oidc-context\";\n\nclass Profile extends React.Component {\n    render() {\n        // `this.props.auth` has all the same properties as the `useAuth` hook\n        const auth = this.props.auth;\n        return \u003cdiv\u003eHello {auth.user?.profile.sub}\u003c/div\u003e;\n    }\n}\n\nexport default withAuth(Profile);\n```\n\n### Call a protected API\n\nAs a child of `AuthProvider` with a user containing an access token:\n\n```jsx\n// src/Posts.jsx\nimport React from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\nconst Posts = () =\u003e {\n    const auth = useAuth();\n    const [posts, setPosts] = React.useState(Array);\n\n    React.useEffect(() =\u003e {\n        (async () =\u003e {\n            try {\n                const token = auth.user?.access_token;\n                const response = await fetch(\"https://api.example.com/posts\", {\n                    headers: {\n                        Authorization: `Bearer ${token}`,\n                    },\n                });\n                setPosts(await response.json());\n            } catch (e) {\n                console.error(e);\n            }\n        })();\n    }, [auth]);\n\n    if (!posts.length) {\n        return \u003cdiv\u003eLoading...\u003c/div\u003e;\n    }\n\n    return (\n        \u003cul\u003e\n        {posts.map((post, index) =\u003e {\n            return \u003cli key={index}\u003e{post}\u003c/li\u003e;\n        })}\n        \u003c/ul\u003e\n    );\n};\n\nexport default Posts;\n```\n\nAs **not** a child of `AuthProvider` (e.g. redux slice) when using local storage\n(`WebStorageStateStore`) for the user containing an access token:\n\n```jsx\n// src/slice.js\nimport { User } from \"oidc-client-ts\"\n\nfunction getUser() {\n    const oidcStorage = localStorage.getItem(`oidc.user:\u003cyour authority\u003e:\u003cyour client id\u003e`)\n    if (!oidcStorage) {\n        return null;\n    }\n\n    return User.fromStorageString(oidcStorage);\n}\n\nexport const getPosts = createAsyncThunk(\n    \"store/getPosts\",\n    async () =\u003e {\n        const user = getUser();\n        const token = user?.access_token;\n        return fetch(\"https://api.example.com/posts\", {\n            headers: {\n                Authorization: `Bearer ${token}`,\n            },\n        });\n    },\n    // ...\n)\n```\n\n### Protect a route\n\nSecure a route component by using the `withAuthenticationRequired` higher-order component. If a user attempts\nto access this route without authentication, they will be redirected to the login page.\n\n```jsx\nimport React from 'react';\nimport { withAuthenticationRequired } from \"react-oidc-context\";\n\nconst PrivateRoute = () =\u003e (\u003cdiv\u003ePrivate\u003c/div\u003e);\n\nexport default withAuthenticationRequired(PrivateRoute, {\n  OnRedirecting: () =\u003e (\u003cdiv\u003eRedirecting to the login page...\u003c/div\u003e)\n});\n```\n\n### Adding event listeners\n\nThe underlying [`UserManagerEvents`](https://authts.github.io/oidc-client-ts/classes/UserManagerEvents.html) instance can be imperatively managed with the `useAuth` hook.\n\n```jsx\n// src/App.jsx\nimport React from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\nfunction App() {\n    const auth = useAuth();\n\n    React.useEffect(() =\u003e {\n        // the `return` is important - addAccessTokenExpiring() returns a cleanup function\n        return auth.events.addAccessTokenExpiring(() =\u003e {\n            if (alert(\"You're about to be signed out due to inactivity. Press continue to stay signed in.\")) {\n                auth.signinSilent();\n            }\n        })\n    }, [auth.events, auth.signinSilent]);\n\n    return \u003cbutton onClick={() =\u003e void auth.signinRedirect()}\u003eLog in\u003c/button\u003e;\n}\n\nexport default App;\n```\n\n### Automatic sign-in\n\nAutomatically sign-in and silently reestablish your previous session, if you close the tab and reopen the application.\n\n```jsx\n// index.jsx\nconst oidcConfig: AuthProviderProps = {\n    ...\n    userStore: new WebStorageStateStore({ store: window.localStorage }),\n};\n```\n\n```jsx\n// src/App.jsx\nimport React from \"react\";\nimport { useAuth, hasAuthParams } from \"react-oidc-context\";\n\nfunction App() {\n    const auth = useAuth();\n    const [hasTriedSignin, setHasTriedSignin] = React.useState(false);\n\n    // automatically sign-in\n    React.useEffect(() =\u003e {\n        if (!hasAuthParams() \u0026\u0026\n            !auth.isAuthenticated \u0026\u0026 !auth.activeNavigator \u0026\u0026 !auth.isLoading \u0026\u0026\n            !hasTriedSignin\n        ) {\n            auth.signinRedirect();\n            setHasTriedSignin(true);\n        }\n    }, [auth, hasTriedSignin]);\n\n    if (auth.isLoading) {\n        return \u003cdiv\u003eSigning you in/out...\u003c/div\u003e;\n    }\n\n    if (!auth.isAuthenticated) {\n        return \u003cdiv\u003eUnable to log in\u003c/div\u003e;\n    }\n\n    return \u003cbutton onClick={() =\u003e void auth.removeUser()}\u003eLog out\u003c/button\u003e;\n}\n\nexport default App;\n```\n\n#### useAutoSignin\n\nUse the `useAutoSignin` hook inside the AuthProvider to automatically sign in.\n\n```jsx\n// src/App.jsx\nimport React from \"react\";\nimport { useAutoSignin } from \"react-oidc-context\";\n\nfunction App() {\n    // If you provide no signinMethod at all, the default is signinRedirect\n    const { isLoading, isAuthenticated, error } = useAutoSignin({signinMethod: \"signinRedirect\"});\n\n    if (isLoading) {\n        return \u003cdiv\u003eSigning you in/out...\u003c/div\u003e;\n    }\n\n    if (!isAuthenticated) {\n        return \u003cdiv\u003eUnable to log in\u003c/div\u003e;\n    }\n\n    if(error) {\n        return \u003cdiv\u003eAn error occured\u003c/div\u003e\n    }\n\n    return \u003cdiv\u003eSigned in successfully\u003c/div\u003e;\n}\n\nexport default App;\n```\n\n## Contributing\n\nWe appreciate feedback and contribution to this repo!\n\n## Influences\n\nThis library is inspired by [oidc-react](https://github.com/bjerkio/oidc-react),\nwhich lacks error handling and\n[auth0-react](https://github.com/auth0/auth0-react), which is focused on auth0.\n\n## License\n\nThis project is licensed under the MIT license. See the\n[LICENSE](https://github.com/authts/react-oidc-context/blob/main/LICENSE) file\nfor more info.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fauthts%2Freact-oidc-context","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fauthts%2Freact-oidc-context","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fauthts%2Freact-oidc-context/lists"}