Skip to content

Repository files navigation

@developertown/oidc-provider

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

VersionDownloads/weekLicense

Installation

Using npm

npm install @developertown/oidc-provider

Using yarn

yarn add @developertown/oidc-provider

Getting Started

Auth0

@developertown/oidc-provider provides a simplified api for integrating Auth0. The simplified api is nearly drop in equilvalent to @auth0/auth0-react

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0Provider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<Auth0Providerdomain="YOUR_AUTH0_DOMAIN"audience="YOUR_API_DOMAIN"clientId="YOUR_AUTH0_CLIENT_ID"redirectUri={window.location.origin}><App/></Auth0Provider>,document.getElementById("app"));

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth0}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth0();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}{" "}<buttononClick={()=>{// optionally pass a returnTo url// https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logoutlogout({extraQueryParams: {returnTo: `${window.location.origin}/logout/callback`,},});// or simply logut to return to the configured redirectUri//logout()}}>
Log out
</button></div>);}else{return(<buttononClick={()=>{//optionally pass a returnTo urlloginWithRedirect({state: {returnTo: `${window.location.href}/login/callback`},});// or take the defaults//loginWithRedirect()}}>
Log in
</button>);}}exportdefaultApp;

AWS Cognito

Configure the SDK by wrapping your application in CognitoProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{CognitoProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<CognitoProviderdomain="YOUR_COGNITO_DOMAIN"issuer="YOUR_COGNITO_ISSUER"clientId="YOUR_COGNITO_CLIENT_ID"redirectUri={window.location.origin}><App/></CognitoProvider>,document.getElementById("app"));

Use the useCongito hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useCongito}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useCongito();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Azure AD B2C

Configure the SDK by wrapping your application in AzureProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{AzureProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AzureProviderdomain="AZURE_AD_TENANT.b2clogin.com/AZURE_AD_TENANT.onmicrosoft.com"policy="b2c_1a_signup_signin"issuer="YOUR_AZURE_AD__ISSUER"clientId="YOUR_AZURE_AD_CLIENT_ID"clientSecret="YOUR_AZURE_AD_CLIENT_SECRET"redirectUri={window.location.origin}><App/></AzureProvider>,document.getElementById("app"));

Use the useAzure hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAzure}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAzure();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Other OpenID Connect

This library can be configured to work with an OpenID Connect authentication provider. Configure the SDK by wrapping your application in OIDCProvider see IdentityModel/oidc-client-js for the full list of options when configuring the OIDCProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{OIDCProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<OIDCProviderauthority={"YOUR_OIDC_DOMAIN"}metadata={{issuer: "YOUR_OIDC_ISSUER",authorization_endpoint: "YOUR_OIDC_AUTHORIZATION_ENDPOINT",token_endpoint: "YOUR_OIDC_TOKEN_ENDPOINT",end_session_endpoint: "YOUR_OIDC_END_SESSION_ENDPOINT",}}client_id={"YOUR_OIDC_CLIENT_ID"}response_type="code"loadUserInfo={false}automaticSilentRenewredirect_uri={window.location.origin}post_logout_redirect_uri={window.location.origin}><App/></OIDCProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

importReactfrom"react";import{withAuthenticationRequired}from"@developertown/oidc-provider";constPrivateRoute=()=><div>Private</div>;exportdefaultwithAuthenticationRequired(PrivateRoute,{// optionally show a message while the authentication provider initializes.onInitializing: ()=><div>Checking for existing login...</div>,// optionally show a message while the user waits to be redirected to the login page.onRedirecting: ()=><div>Redirecting you to the login page...</div>,// optionally show a message login fails.onError: (error: Error)=><div>{error.message}</div>,// optionally pass parameters to `loginWithRedirect` for example a returnTo locationloginWithRedirectParams: ()=>({state: {returnTo: window.location.href},}),});

Call an API

Call a protected API with an Access Token:

importReact,{useEffect,useState}from"react";import{useAuth}from"@developertown/oidc-provider";constPosts=()=>{const{ getAccessTokenSilently }=useAuth();const[posts,setPosts]=useState(null);useEffect(()=>{(async()=>{try{consttoken=awaitgetAccessTokenSilently();constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[getAccessTokenSilently]);if(!posts){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

Events

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0ProviderasAuthenticationProvider,AppState,}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AuthenticationProviderdomain="YOUR_DOMAIN"clientId="YOUR_CLIENT_ID"redirectUri={window.location.origin}useRefreshTokensonAccessTokenChanged={(accessToken: string)=>{/* Do something with the accessToken*/// dispatch(accessTokenChanged(accessToken))// NOTE: this event may not be needed since getAccessTokenSilently() will always grab the latest access token// or perform a silent refresh to get a fresh one}}onAccessTokenExpiring={()=>{// Let the user know their session is expiring// NOTE: when useRefreshTokens is true accessTokens will be automatically refreshed}}onAccessTokenExpired={()=>{// Let the user know their session has expired// NOTE: when useRefreshTokens is true as long as the silent refresh occurs successfully the token will not expire}}onAccessTokenRefreshError={(error: Error)=>{// Handle errors when silently refreshing access tokens. Only applies when useRefreshTokens is true}}onRedirectCallback={(appState?: AppState)=>{// Perform action after redirecting from the authentication provider// NOTE: if no onRedirectCallback is provided the default behavior iswindow.history.replaceState({},document.title,appState?.returnTo||window.location.pathname);}}><App/></AuthenticationProvider>,document.getElementById("app"));

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

Topics

Resources

Code of conduct

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
developertown/oidc-provider · GitHub
Skip to content

Repository files navigation

@developertown/oidc-provider

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

VersionDownloads/weekLicense

Installation

Using npm

npm install @developertown/oidc-provider

Using yarn

yarn add @developertown/oidc-provider

Getting Started

Auth0

@developertown/oidc-provider provides a simplified api for integrating Auth0. The simplified api is nearly drop in equilvalent to @auth0/auth0-react

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0Provider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<Auth0Providerdomain="YOUR_AUTH0_DOMAIN"audience="YOUR_API_DOMAIN"clientId="YOUR_AUTH0_CLIENT_ID"redirectUri={window.location.origin}><App/></Auth0Provider>,document.getElementById("app"));

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth0}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth0();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}{" "}<buttononClick={()=>{// optionally pass a returnTo url// https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logoutlogout({extraQueryParams: {returnTo: `${window.location.origin}/logout/callback`,},});// or simply logut to return to the configured redirectUri//logout()}}>
Log out
</button></div>);}else{return(<buttononClick={()=>{//optionally pass a returnTo urlloginWithRedirect({state: {returnTo: `${window.location.href}/login/callback`},});// or take the defaults//loginWithRedirect()}}>
Log in
</button>);}}exportdefaultApp;

AWS Cognito

Configure the SDK by wrapping your application in CognitoProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{CognitoProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<CognitoProviderdomain="YOUR_COGNITO_DOMAIN"issuer="YOUR_COGNITO_ISSUER"clientId="YOUR_COGNITO_CLIENT_ID"redirectUri={window.location.origin}><App/></CognitoProvider>,document.getElementById("app"));

Use the useCongito hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useCongito}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useCongito();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Azure AD B2C

Configure the SDK by wrapping your application in AzureProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{AzureProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AzureProviderdomain="AZURE_AD_TENANT.b2clogin.com/AZURE_AD_TENANT.onmicrosoft.com"policy="b2c_1a_signup_signin"issuer="YOUR_AZURE_AD__ISSUER"clientId="YOUR_AZURE_AD_CLIENT_ID"clientSecret="YOUR_AZURE_AD_CLIENT_SECRET"redirectUri={window.location.origin}><App/></AzureProvider>,document.getElementById("app"));

Use the useAzure hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAzure}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAzure();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Other OpenID Connect

This library can be configured to work with an OpenID Connect authentication provider. Configure the SDK by wrapping your application in OIDCProvider see IdentityModel/oidc-client-js for the full list of options when configuring the OIDCProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{OIDCProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<OIDCProviderauthority={"YOUR_OIDC_DOMAIN"}metadata={{issuer: "YOUR_OIDC_ISSUER",authorization_endpoint: "YOUR_OIDC_AUTHORIZATION_ENDPOINT",token_endpoint: "YOUR_OIDC_TOKEN_ENDPOINT",end_session_endpoint: "YOUR_OIDC_END_SESSION_ENDPOINT",}}client_id={"YOUR_OIDC_CLIENT_ID"}response_type="code"loadUserInfo={false}automaticSilentRenewredirect_uri={window.location.origin}post_logout_redirect_uri={window.location.origin}><App/></OIDCProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

importReactfrom"react";import{withAuthenticationRequired}from"@developertown/oidc-provider";constPrivateRoute=()=><div>Private</div>;exportdefaultwithAuthenticationRequired(PrivateRoute,{// optionally show a message while the authentication provider initializes.onInitializing: ()=><div>Checking for existing login...</div>,// optionally show a message while the user waits to be redirected to the login page.onRedirecting: ()=><div>Redirecting you to the login page...</div>,// optionally show a message login fails.onError: (error: Error)=><div>{error.message}</div>,// optionally pass parameters to `loginWithRedirect` for example a returnTo locationloginWithRedirectParams: ()=>({state: {returnTo: window.location.href},}),});

Call an API

Call a protected API with an Access Token:

importReact,{useEffect,useState}from"react";import{useAuth}from"@developertown/oidc-provider";constPosts=()=>{const{ getAccessTokenSilently }=useAuth();const[posts,setPosts]=useState(null);useEffect(()=>{(async()=>{try{consttoken=awaitgetAccessTokenSilently();constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[getAccessTokenSilently]);if(!posts){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

Events

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0ProviderasAuthenticationProvider,AppState,}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AuthenticationProviderdomain="YOUR_DOMAIN"clientId="YOUR_CLIENT_ID"redirectUri={window.location.origin}useRefreshTokensonAccessTokenChanged={(accessToken: string)=>{/* Do something with the accessToken*/// dispatch(accessTokenChanged(accessToken))// NOTE: this event may not be needed since getAccessTokenSilently() will always grab the latest access token// or perform a silent refresh to get a fresh one}}onAccessTokenExpiring={()=>{// Let the user know their session is expiring// NOTE: when useRefreshTokens is true accessTokens will be automatically refreshed}}onAccessTokenExpired={()=>{// Let the user know their session has expired// NOTE: when useRefreshTokens is true as long as the silent refresh occurs successfully the token will not expire}}onAccessTokenRefreshError={(error: Error)=>{// Handle errors when silently refreshing access tokens. Only applies when useRefreshTokens is true}}onRedirectCallback={(appState?: AppState)=>{// Perform action after redirecting from the authentication provider// NOTE: if no onRedirectCallback is provided the default behavior iswindow.history.replaceState({},document.title,appState?.returnTo||window.location.pathname);}}><App/></AuthenticationProvider>,document.getElementById("app"));

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

Topics

Resources

Code of conduct

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' developertown/oidc-provider · GitHub
Skip to content

Repository files navigation

@developertown/oidc-provider

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

VersionDownloads/weekLicense

Installation

Using npm

npm install @developertown/oidc-provider

Using yarn

yarn add @developertown/oidc-provider

Getting Started

Auth0

@developertown/oidc-provider provides a simplified api for integrating Auth0. The simplified api is nearly drop in equilvalent to @auth0/auth0-react

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0Provider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<Auth0Providerdomain="YOUR_AUTH0_DOMAIN"audience="YOUR_API_DOMAIN"clientId="YOUR_AUTH0_CLIENT_ID"redirectUri={window.location.origin}><App/></Auth0Provider>,document.getElementById("app"));

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth0}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth0();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}{" "}<buttononClick={()=>{// optionally pass a returnTo url// https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logoutlogout({extraQueryParams: {returnTo: `${window.location.origin}/logout/callback`,},});// or simply logut to return to the configured redirectUri//logout()}}>
Log out
</button></div>);}else{return(<buttononClick={()=>{//optionally pass a returnTo urlloginWithRedirect({state: {returnTo: `${window.location.href}/login/callback`},});// or take the defaults//loginWithRedirect()}}>
Log in
</button>);}}exportdefaultApp;

AWS Cognito

Configure the SDK by wrapping your application in CognitoProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{CognitoProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<CognitoProviderdomain="YOUR_COGNITO_DOMAIN"issuer="YOUR_COGNITO_ISSUER"clientId="YOUR_COGNITO_CLIENT_ID"redirectUri={window.location.origin}><App/></CognitoProvider>,document.getElementById("app"));

Use the useCongito hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useCongito}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useCongito();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Azure AD B2C

Configure the SDK by wrapping your application in AzureProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{AzureProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AzureProviderdomain="AZURE_AD_TENANT.b2clogin.com/AZURE_AD_TENANT.onmicrosoft.com"policy="b2c_1a_signup_signin"issuer="YOUR_AZURE_AD__ISSUER"clientId="YOUR_AZURE_AD_CLIENT_ID"clientSecret="YOUR_AZURE_AD_CLIENT_SECRET"redirectUri={window.location.origin}><App/></AzureProvider>,document.getElementById("app"));

Use the useAzure hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAzure}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAzure();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Other OpenID Connect

This library can be configured to work with an OpenID Connect authentication provider. Configure the SDK by wrapping your application in OIDCProvider see IdentityModel/oidc-client-js for the full list of options when configuring the OIDCProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{OIDCProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<OIDCProviderauthority={"YOUR_OIDC_DOMAIN"}metadata={{issuer: "YOUR_OIDC_ISSUER",authorization_endpoint: "YOUR_OIDC_AUTHORIZATION_ENDPOINT",token_endpoint: "YOUR_OIDC_TOKEN_ENDPOINT",end_session_endpoint: "YOUR_OIDC_END_SESSION_ENDPOINT",}}client_id={"YOUR_OIDC_CLIENT_ID"}response_type="code"loadUserInfo={false}automaticSilentRenewredirect_uri={window.location.origin}post_logout_redirect_uri={window.location.origin}><App/></OIDCProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

importReactfrom"react";import{withAuthenticationRequired}from"@developertown/oidc-provider";constPrivateRoute=()=><div>Private</div>;exportdefaultwithAuthenticationRequired(PrivateRoute,{// optionally show a message while the authentication provider initializes.onInitializing: ()=><div>Checking for existing login...</div>,// optionally show a message while the user waits to be redirected to the login page.onRedirecting: ()=><div>Redirecting you to the login page...</div>,// optionally show a message login fails.onError: (error: Error)=><div>{error.message}</div>,// optionally pass parameters to `loginWithRedirect` for example a returnTo locationloginWithRedirectParams: ()=>({state: {returnTo: window.location.href},}),});

Call an API

Call a protected API with an Access Token:

importReact,{useEffect,useState}from"react";import{useAuth}from"@developertown/oidc-provider";constPosts=()=>{const{ getAccessTokenSilently }=useAuth();const[posts,setPosts]=useState(null);useEffect(()=>{(async()=>{try{consttoken=awaitgetAccessTokenSilently();constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[getAccessTokenSilently]);if(!posts){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

Events

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0ProviderasAuthenticationProvider,AppState,}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AuthenticationProviderdomain="YOUR_DOMAIN"clientId="YOUR_CLIENT_ID"redirectUri={window.location.origin}useRefreshTokensonAccessTokenChanged={(accessToken: string)=>{/* Do something with the accessToken*/// dispatch(accessTokenChanged(accessToken))// NOTE: this event may not be needed since getAccessTokenSilently() will always grab the latest access token// or perform a silent refresh to get a fresh one}}onAccessTokenExpiring={()=>{// Let the user know their session is expiring// NOTE: when useRefreshTokens is true accessTokens will be automatically refreshed}}onAccessTokenExpired={()=>{// Let the user know their session has expired// NOTE: when useRefreshTokens is true as long as the silent refresh occurs successfully the token will not expire}}onAccessTokenRefreshError={(error: Error)=>{// Handle errors when silently refreshing access tokens. Only applies when useRefreshTokens is true}}onRedirectCallback={(appState?: AppState)=>{// Perform action after redirecting from the authentication provider// NOTE: if no onRedirectCallback is provided the default behavior iswindow.history.replaceState({},document.title,appState?.returnTo||window.location.pathname);}}><App/></AuthenticationProvider>,document.getElementById("app"));

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

Topics

Resources

Code of conduct

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' developertown/oidc-provider · GitHub
Skip to content

Repository files navigation

@developertown/oidc-provider

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

VersionDownloads/weekLicense

Installation

Using npm

npm install @developertown/oidc-provider

Using yarn

yarn add @developertown/oidc-provider

Getting Started

Auth0

@developertown/oidc-provider provides a simplified api for integrating Auth0. The simplified api is nearly drop in equilvalent to @auth0/auth0-react

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0Provider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<Auth0Providerdomain="YOUR_AUTH0_DOMAIN"audience="YOUR_API_DOMAIN"clientId="YOUR_AUTH0_CLIENT_ID"redirectUri={window.location.origin}><App/></Auth0Provider>,document.getElementById("app"));

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth0}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth0();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}{" "}<buttononClick={()=>{// optionally pass a returnTo url// https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logoutlogout({extraQueryParams: {returnTo: `${window.location.origin}/logout/callback`,},});// or simply logut to return to the configured redirectUri//logout()}}>
Log out
</button></div>);}else{return(<buttononClick={()=>{//optionally pass a returnTo urlloginWithRedirect({state: {returnTo: `${window.location.href}/login/callback`},});// or take the defaults//loginWithRedirect()}}>
Log in
</button>);}}exportdefaultApp;

AWS Cognito

Configure the SDK by wrapping your application in CognitoProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{CognitoProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<CognitoProviderdomain="YOUR_COGNITO_DOMAIN"issuer="YOUR_COGNITO_ISSUER"clientId="YOUR_COGNITO_CLIENT_ID"redirectUri={window.location.origin}><App/></CognitoProvider>,document.getElementById("app"));

Use the useCongito hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useCongito}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useCongito();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Azure AD B2C

Configure the SDK by wrapping your application in AzureProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{AzureProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AzureProviderdomain="AZURE_AD_TENANT.b2clogin.com/AZURE_AD_TENANT.onmicrosoft.com"policy="b2c_1a_signup_signin"issuer="YOUR_AZURE_AD__ISSUER"clientId="YOUR_AZURE_AD_CLIENT_ID"clientSecret="YOUR_AZURE_AD_CLIENT_SECRET"redirectUri={window.location.origin}><App/></AzureProvider>,document.getElementById("app"));

Use the useAzure hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAzure}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAzure();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Other OpenID Connect

This library can be configured to work with an OpenID Connect authentication provider. Configure the SDK by wrapping your application in OIDCProvider see IdentityModel/oidc-client-js for the full list of options when configuring the OIDCProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{OIDCProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<OIDCProviderauthority={"YOUR_OIDC_DOMAIN"}metadata={{issuer: "YOUR_OIDC_ISSUER",authorization_endpoint: "YOUR_OIDC_AUTHORIZATION_ENDPOINT",token_endpoint: "YOUR_OIDC_TOKEN_ENDPOINT",end_session_endpoint: "YOUR_OIDC_END_SESSION_ENDPOINT",}}client_id={"YOUR_OIDC_CLIENT_ID"}response_type="code"loadUserInfo={false}automaticSilentRenewredirect_uri={window.location.origin}post_logout_redirect_uri={window.location.origin}><App/></OIDCProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

importReactfrom"react";import{withAuthenticationRequired}from"@developertown/oidc-provider";constPrivateRoute=()=><div>Private</div>;exportdefaultwithAuthenticationRequired(PrivateRoute,{// optionally show a message while the authentication provider initializes.onInitializing: ()=><div>Checking for existing login...</div>,// optionally show a message while the user waits to be redirected to the login page.onRedirecting: ()=><div>Redirecting you to the login page...</div>,// optionally show a message login fails.onError: (error: Error)=><div>{error.message}</div>,// optionally pass parameters to `loginWithRedirect` for example a returnTo locationloginWithRedirectParams: ()=>({state: {returnTo: window.location.href},}),});

Call an API

Call a protected API with an Access Token:

importReact,{useEffect,useState}from"react";import{useAuth}from"@developertown/oidc-provider";constPosts=()=>{const{ getAccessTokenSilently }=useAuth();const[posts,setPosts]=useState(null);useEffect(()=>{(async()=>{try{consttoken=awaitgetAccessTokenSilently();constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[getAccessTokenSilently]);if(!posts){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

Events

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0ProviderasAuthenticationProvider,AppState,}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AuthenticationProviderdomain="YOUR_DOMAIN"clientId="YOUR_CLIENT_ID"redirectUri={window.location.origin}useRefreshTokensonAccessTokenChanged={(accessToken: string)=>{/* Do something with the accessToken*/// dispatch(accessTokenChanged(accessToken))// NOTE: this event may not be needed since getAccessTokenSilently() will always grab the latest access token// or perform a silent refresh to get a fresh one}}onAccessTokenExpiring={()=>{// Let the user know their session is expiring// NOTE: when useRefreshTokens is true accessTokens will be automatically refreshed}}onAccessTokenExpired={()=>{// Let the user know their session has expired// NOTE: when useRefreshTokens is true as long as the silent refresh occurs successfully the token will not expire}}onAccessTokenRefreshError={(error: Error)=>{// Handle errors when silently refreshing access tokens. Only applies when useRefreshTokens is true}}onRedirectCallback={(appState?: AppState)=>{// Perform action after redirecting from the authentication provider// NOTE: if no onRedirectCallback is provided the default behavior iswindow.history.replaceState({},document.title,appState?.returnTo||window.location.pathname);}}><App/></AuthenticationProvider>,document.getElementById("app"));

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

Topics

Resources

Code of conduct

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' developertown/oidc-provider · GitHub
Skip to content

Repository files navigation

@developertown/oidc-provider

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

VersionDownloads/weekLicense

Installation

Using npm

npm install @developertown/oidc-provider

Using yarn

yarn add @developertown/oidc-provider

Getting Started

Auth0

@developertown/oidc-provider provides a simplified api for integrating Auth0. The simplified api is nearly drop in equilvalent to @auth0/auth0-react

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0Provider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<Auth0Providerdomain="YOUR_AUTH0_DOMAIN"audience="YOUR_API_DOMAIN"clientId="YOUR_AUTH0_CLIENT_ID"redirectUri={window.location.origin}><App/></Auth0Provider>,document.getElementById("app"));

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth0}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth0();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}{" "}<buttononClick={()=>{// optionally pass a returnTo url// https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logoutlogout({extraQueryParams: {returnTo: `${window.location.origin}/logout/callback`,},});// or simply logut to return to the configured redirectUri//logout()}}>
Log out
</button></div>);}else{return(<buttononClick={()=>{//optionally pass a returnTo urlloginWithRedirect({state: {returnTo: `${window.location.href}/login/callback`},});// or take the defaults//loginWithRedirect()}}>
Log in
</button>);}}exportdefaultApp;

AWS Cognito

Configure the SDK by wrapping your application in CognitoProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{CognitoProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<CognitoProviderdomain="YOUR_COGNITO_DOMAIN"issuer="YOUR_COGNITO_ISSUER"clientId="YOUR_COGNITO_CLIENT_ID"redirectUri={window.location.origin}><App/></CognitoProvider>,document.getElementById("app"));

Use the useCongito hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useCongito}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useCongito();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Azure AD B2C

Configure the SDK by wrapping your application in AzureProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{AzureProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AzureProviderdomain="AZURE_AD_TENANT.b2clogin.com/AZURE_AD_TENANT.onmicrosoft.com"policy="b2c_1a_signup_signin"issuer="YOUR_AZURE_AD__ISSUER"clientId="YOUR_AZURE_AD_CLIENT_ID"clientSecret="YOUR_AZURE_AD_CLIENT_SECRET"redirectUri={window.location.origin}><App/></AzureProvider>,document.getElementById("app"));

Use the useAzure hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAzure}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAzure();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Other OpenID Connect

This library can be configured to work with an OpenID Connect authentication provider. Configure the SDK by wrapping your application in OIDCProvider see IdentityModel/oidc-client-js for the full list of options when configuring the OIDCProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{OIDCProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<OIDCProviderauthority={"YOUR_OIDC_DOMAIN"}metadata={{issuer: "YOUR_OIDC_ISSUER",authorization_endpoint: "YOUR_OIDC_AUTHORIZATION_ENDPOINT",token_endpoint: "YOUR_OIDC_TOKEN_ENDPOINT",end_session_endpoint: "YOUR_OIDC_END_SESSION_ENDPOINT",}}client_id={"YOUR_OIDC_CLIENT_ID"}response_type="code"loadUserInfo={false}automaticSilentRenewredirect_uri={window.location.origin}post_logout_redirect_uri={window.location.origin}><App/></OIDCProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

importReactfrom"react";import{withAuthenticationRequired}from"@developertown/oidc-provider";constPrivateRoute=()=><div>Private</div>;exportdefaultwithAuthenticationRequired(PrivateRoute,{// optionally show a message while the authentication provider initializes.onInitializing: ()=><div>Checking for existing login...</div>,// optionally show a message while the user waits to be redirected to the login page.onRedirecting: ()=><div>Redirecting you to the login page...</div>,// optionally show a message login fails.onError: (error: Error)=><div>{error.message}</div>,// optionally pass parameters to `loginWithRedirect` for example a returnTo locationloginWithRedirectParams: ()=>({state: {returnTo: window.location.href},}),});

Call an API

Call a protected API with an Access Token:

importReact,{useEffect,useState}from"react";import{useAuth}from"@developertown/oidc-provider";constPosts=()=>{const{ getAccessTokenSilently }=useAuth();const[posts,setPosts]=useState(null);useEffect(()=>{(async()=>{try{consttoken=awaitgetAccessTokenSilently();constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[getAccessTokenSilently]);if(!posts){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

Events

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0ProviderasAuthenticationProvider,AppState,}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AuthenticationProviderdomain="YOUR_DOMAIN"clientId="YOUR_CLIENT_ID"redirectUri={window.location.origin}useRefreshTokensonAccessTokenChanged={(accessToken: string)=>{/* Do something with the accessToken*/// dispatch(accessTokenChanged(accessToken))// NOTE: this event may not be needed since getAccessTokenSilently() will always grab the latest access token// or perform a silent refresh to get a fresh one}}onAccessTokenExpiring={()=>{// Let the user know their session is expiring// NOTE: when useRefreshTokens is true accessTokens will be automatically refreshed}}onAccessTokenExpired={()=>{// Let the user know their session has expired// NOTE: when useRefreshTokens is true as long as the silent refresh occurs successfully the token will not expire}}onAccessTokenRefreshError={(error: Error)=>{// Handle errors when silently refreshing access tokens. Only applies when useRefreshTokens is true}}onRedirectCallback={(appState?: AppState)=>{// Perform action after redirecting from the authentication provider// NOTE: if no onRedirectCallback is provided the default behavior iswindow.history.replaceState({},document.title,appState?.returnTo||window.location.pathname);}}><App/></AuthenticationProvider>,document.getElementById("app"));

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

Topics

Resources

Code of conduct

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' developertown/oidc-provider · GitHub
Skip to content

Repository files navigation

@developertown/oidc-provider

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

VersionDownloads/weekLicense

Installation

Using npm

npm install @developertown/oidc-provider

Using yarn

yarn add @developertown/oidc-provider

Getting Started

Auth0

@developertown/oidc-provider provides a simplified api for integrating Auth0. The simplified api is nearly drop in equilvalent to @auth0/auth0-react

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0Provider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<Auth0Providerdomain="YOUR_AUTH0_DOMAIN"audience="YOUR_API_DOMAIN"clientId="YOUR_AUTH0_CLIENT_ID"redirectUri={window.location.origin}><App/></Auth0Provider>,document.getElementById("app"));

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth0}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth0();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}{" "}<buttononClick={()=>{// optionally pass a returnTo url// https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logoutlogout({extraQueryParams: {returnTo: `${window.location.origin}/logout/callback`,},});// or simply logut to return to the configured redirectUri//logout()}}>
Log out
</button></div>);}else{return(<buttononClick={()=>{//optionally pass a returnTo urlloginWithRedirect({state: {returnTo: `${window.location.href}/login/callback`},});// or take the defaults//loginWithRedirect()}}>
Log in
</button>);}}exportdefaultApp;

AWS Cognito

Configure the SDK by wrapping your application in CognitoProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{CognitoProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<CognitoProviderdomain="YOUR_COGNITO_DOMAIN"issuer="YOUR_COGNITO_ISSUER"clientId="YOUR_COGNITO_CLIENT_ID"redirectUri={window.location.origin}><App/></CognitoProvider>,document.getElementById("app"));

Use the useCongito hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useCongito}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useCongito();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Azure AD B2C

Configure the SDK by wrapping your application in AzureProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{AzureProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AzureProviderdomain="AZURE_AD_TENANT.b2clogin.com/AZURE_AD_TENANT.onmicrosoft.com"policy="b2c_1a_signup_signin"issuer="YOUR_AZURE_AD__ISSUER"clientId="YOUR_AZURE_AD_CLIENT_ID"clientSecret="YOUR_AZURE_AD_CLIENT_SECRET"redirectUri={window.location.origin}><App/></AzureProvider>,document.getElementById("app"));

Use the useAzure hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAzure}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAzure();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Other OpenID Connect

This library can be configured to work with an OpenID Connect authentication provider. Configure the SDK by wrapping your application in OIDCProvider see IdentityModel/oidc-client-js for the full list of options when configuring the OIDCProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{OIDCProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<OIDCProviderauthority={"YOUR_OIDC_DOMAIN"}metadata={{issuer: "YOUR_OIDC_ISSUER",authorization_endpoint: "YOUR_OIDC_AUTHORIZATION_ENDPOINT",token_endpoint: "YOUR_OIDC_TOKEN_ENDPOINT",end_session_endpoint: "YOUR_OIDC_END_SESSION_ENDPOINT",}}client_id={"YOUR_OIDC_CLIENT_ID"}response_type="code"loadUserInfo={false}automaticSilentRenewredirect_uri={window.location.origin}post_logout_redirect_uri={window.location.origin}><App/></OIDCProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

importReactfrom"react";import{withAuthenticationRequired}from"@developertown/oidc-provider";constPrivateRoute=()=><div>Private</div>;exportdefaultwithAuthenticationRequired(PrivateRoute,{// optionally show a message while the authentication provider initializes.onInitializing: ()=><div>Checking for existing login...</div>,// optionally show a message while the user waits to be redirected to the login page.onRedirecting: ()=><div>Redirecting you to the login page...</div>,// optionally show a message login fails.onError: (error: Error)=><div>{error.message}</div>,// optionally pass parameters to `loginWithRedirect` for example a returnTo locationloginWithRedirectParams: ()=>({state: {returnTo: window.location.href},}),});

Call an API

Call a protected API with an Access Token:

importReact,{useEffect,useState}from"react";import{useAuth}from"@developertown/oidc-provider";constPosts=()=>{const{ getAccessTokenSilently }=useAuth();const[posts,setPosts]=useState(null);useEffect(()=>{(async()=>{try{consttoken=awaitgetAccessTokenSilently();constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[getAccessTokenSilently]);if(!posts){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

Events

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0ProviderasAuthenticationProvider,AppState,}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AuthenticationProviderdomain="YOUR_DOMAIN"clientId="YOUR_CLIENT_ID"redirectUri={window.location.origin}useRefreshTokensonAccessTokenChanged={(accessToken: string)=>{/* Do something with the accessToken*/// dispatch(accessTokenChanged(accessToken))// NOTE: this event may not be needed since getAccessTokenSilently() will always grab the latest access token// or perform a silent refresh to get a fresh one}}onAccessTokenExpiring={()=>{// Let the user know their session is expiring// NOTE: when useRefreshTokens is true accessTokens will be automatically refreshed}}onAccessTokenExpired={()=>{// Let the user know their session has expired// NOTE: when useRefreshTokens is true as long as the silent refresh occurs successfully the token will not expire}}onAccessTokenRefreshError={(error: Error)=>{// Handle errors when silently refreshing access tokens. Only applies when useRefreshTokens is true}}onRedirectCallback={(appState?: AppState)=>{// Perform action after redirecting from the authentication provider// NOTE: if no onRedirectCallback is provided the default behavior iswindow.history.replaceState({},document.title,appState?.returnTo||window.location.pathname);}}><App/></AuthenticationProvider>,document.getElementById("app"));

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

Topics

Resources

Code of conduct

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' developertown/oidc-provider · GitHub
Skip to content

Repository files navigation

@developertown/oidc-provider

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

VersionDownloads/weekLicense

Installation

Using npm

npm install @developertown/oidc-provider

Using yarn

yarn add @developertown/oidc-provider

Getting Started

Auth0

@developertown/oidc-provider provides a simplified api for integrating Auth0. The simplified api is nearly drop in equilvalent to @auth0/auth0-react

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0Provider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<Auth0Providerdomain="YOUR_AUTH0_DOMAIN"audience="YOUR_API_DOMAIN"clientId="YOUR_AUTH0_CLIENT_ID"redirectUri={window.location.origin}><App/></Auth0Provider>,document.getElementById("app"));

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth0}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth0();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}{" "}<buttononClick={()=>{// optionally pass a returnTo url// https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logoutlogout({extraQueryParams: {returnTo: `${window.location.origin}/logout/callback`,},});// or simply logut to return to the configured redirectUri//logout()}}>
Log out
</button></div>);}else{return(<buttononClick={()=>{//optionally pass a returnTo urlloginWithRedirect({state: {returnTo: `${window.location.href}/login/callback`},});// or take the defaults//loginWithRedirect()}}>
Log in
</button>);}}exportdefaultApp;

AWS Cognito

Configure the SDK by wrapping your application in CognitoProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{CognitoProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<CognitoProviderdomain="YOUR_COGNITO_DOMAIN"issuer="YOUR_COGNITO_ISSUER"clientId="YOUR_COGNITO_CLIENT_ID"redirectUri={window.location.origin}><App/></CognitoProvider>,document.getElementById("app"));

Use the useCongito hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useCongito}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useCongito();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Azure AD B2C

Configure the SDK by wrapping your application in AzureProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{AzureProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AzureProviderdomain="AZURE_AD_TENANT.b2clogin.com/AZURE_AD_TENANT.onmicrosoft.com"policy="b2c_1a_signup_signin"issuer="YOUR_AZURE_AD__ISSUER"clientId="YOUR_AZURE_AD_CLIENT_ID"clientSecret="YOUR_AZURE_AD_CLIENT_SECRET"redirectUri={window.location.origin}><App/></AzureProvider>,document.getElementById("app"));

Use the useAzure hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAzure}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAzure();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Other OpenID Connect

This library can be configured to work with an OpenID Connect authentication provider. Configure the SDK by wrapping your application in OIDCProvider see IdentityModel/oidc-client-js for the full list of options when configuring the OIDCProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{OIDCProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<OIDCProviderauthority={"YOUR_OIDC_DOMAIN"}metadata={{issuer: "YOUR_OIDC_ISSUER",authorization_endpoint: "YOUR_OIDC_AUTHORIZATION_ENDPOINT",token_endpoint: "YOUR_OIDC_TOKEN_ENDPOINT",end_session_endpoint: "YOUR_OIDC_END_SESSION_ENDPOINT",}}client_id={"YOUR_OIDC_CLIENT_ID"}response_type="code"loadUserInfo={false}automaticSilentRenewredirect_uri={window.location.origin}post_logout_redirect_uri={window.location.origin}><App/></OIDCProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

importReactfrom"react";import{withAuthenticationRequired}from"@developertown/oidc-provider";constPrivateRoute=()=><div>Private</div>;exportdefaultwithAuthenticationRequired(PrivateRoute,{// optionally show a message while the authentication provider initializes.onInitializing: ()=><div>Checking for existing login...</div>,// optionally show a message while the user waits to be redirected to the login page.onRedirecting: ()=><div>Redirecting you to the login page...</div>,// optionally show a message login fails.onError: (error: Error)=><div>{error.message}</div>,// optionally pass parameters to `loginWithRedirect` for example a returnTo locationloginWithRedirectParams: ()=>({state: {returnTo: window.location.href},}),});

Call an API

Call a protected API with an Access Token:

importReact,{useEffect,useState}from"react";import{useAuth}from"@developertown/oidc-provider";constPosts=()=>{const{ getAccessTokenSilently }=useAuth();const[posts,setPosts]=useState(null);useEffect(()=>{(async()=>{try{consttoken=awaitgetAccessTokenSilently();constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[getAccessTokenSilently]);if(!posts){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

Events

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0ProviderasAuthenticationProvider,AppState,}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AuthenticationProviderdomain="YOUR_DOMAIN"clientId="YOUR_CLIENT_ID"redirectUri={window.location.origin}useRefreshTokensonAccessTokenChanged={(accessToken: string)=>{/* Do something with the accessToken*/// dispatch(accessTokenChanged(accessToken))// NOTE: this event may not be needed since getAccessTokenSilently() will always grab the latest access token// or perform a silent refresh to get a fresh one}}onAccessTokenExpiring={()=>{// Let the user know their session is expiring// NOTE: when useRefreshTokens is true accessTokens will be automatically refreshed}}onAccessTokenExpired={()=>{// Let the user know their session has expired// NOTE: when useRefreshTokens is true as long as the silent refresh occurs successfully the token will not expire}}onAccessTokenRefreshError={(error: Error)=>{// Handle errors when silently refreshing access tokens. Only applies when useRefreshTokens is true}}onRedirectCallback={(appState?: AppState)=>{// Perform action after redirecting from the authentication provider// NOTE: if no onRedirectCallback is provided the default behavior iswindow.history.replaceState({},document.title,appState?.returnTo||window.location.pathname);}}><App/></AuthenticationProvider>,document.getElementById("app"));

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

Topics

Resources

Code of conduct

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); developertown/oidc-provider · GitHub
Skip to content

Repository files navigation

@developertown/oidc-provider

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

VersionDownloads/weekLicense

Installation

Using npm

npm install @developertown/oidc-provider

Using yarn

yarn add @developertown/oidc-provider

Getting Started

Auth0

@developertown/oidc-provider provides a simplified api for integrating Auth0. The simplified api is nearly drop in equilvalent to @auth0/auth0-react

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0Provider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<Auth0Providerdomain="YOUR_AUTH0_DOMAIN"audience="YOUR_API_DOMAIN"clientId="YOUR_AUTH0_CLIENT_ID"redirectUri={window.location.origin}><App/></Auth0Provider>,document.getElementById("app"));

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth0}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth0();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}{" "}<buttononClick={()=>{// optionally pass a returnTo url// https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logoutlogout({extraQueryParams: {returnTo: `${window.location.origin}/logout/callback`,},});// or simply logut to return to the configured redirectUri//logout()}}>
Log out
</button></div>);}else{return(<buttononClick={()=>{//optionally pass a returnTo urlloginWithRedirect({state: {returnTo: `${window.location.href}/login/callback`},});// or take the defaults//loginWithRedirect()}}>
Log in
</button>);}}exportdefaultApp;

AWS Cognito

Configure the SDK by wrapping your application in CognitoProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{CognitoProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<CognitoProviderdomain="YOUR_COGNITO_DOMAIN"issuer="YOUR_COGNITO_ISSUER"clientId="YOUR_COGNITO_CLIENT_ID"redirectUri={window.location.origin}><App/></CognitoProvider>,document.getElementById("app"));

Use the useCongito hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useCongito}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useCongito();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Azure AD B2C

Configure the SDK by wrapping your application in AzureProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{AzureProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AzureProviderdomain="AZURE_AD_TENANT.b2clogin.com/AZURE_AD_TENANT.onmicrosoft.com"policy="b2c_1a_signup_signin"issuer="YOUR_AZURE_AD__ISSUER"clientId="YOUR_AZURE_AD_CLIENT_ID"clientSecret="YOUR_AZURE_AD_CLIENT_SECRET"redirectUri={window.location.origin}><App/></AzureProvider>,document.getElementById("app"));

Use the useAzure hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAzure}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAzure();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Other OpenID Connect

This library can be configured to work with an OpenID Connect authentication provider. Configure the SDK by wrapping your application in OIDCProvider see IdentityModel/oidc-client-js for the full list of options when configuring the OIDCProvider:

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{OIDCProvider}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<OIDCProviderauthority={"YOUR_OIDC_DOMAIN"}metadata={{issuer: "YOUR_OIDC_ISSUER",authorization_endpoint: "YOUR_OIDC_AUTHORIZATION_ENDPOINT",token_endpoint: "YOUR_OIDC_TOKEN_ENDPOINT",end_session_endpoint: "YOUR_OIDC_END_SESSION_ENDPOINT",}}client_id={"YOUR_OIDC_CLIENT_ID"}response_type="code"loadUserInfo={false}automaticSilentRenewredirect_uri={window.location.origin}post_logout_redirect_uri={window.location.origin}><App/></OIDCProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.jsimportReactfrom"react";import{useAuth}from"@developertown/oidc-provider";functionApp(){const{
isLoading,
isAuthenticated,
error,
user,
loginWithRedirect,
logout,}=useAuth();if(isLoading){return<div>Loading...</div>;}if(error){return<div>Oops... {error.message}</div>;}if(isAuthenticated){return(<div>
Hello {user.name}<buttononClick={()=>logout()}>Log out</button></div>);}else{return<buttononClick={loginWithRedirect}>Log in</button>;}}exportdefaultApp;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

importReactfrom"react";import{withAuthenticationRequired}from"@developertown/oidc-provider";constPrivateRoute=()=><div>Private</div>;exportdefaultwithAuthenticationRequired(PrivateRoute,{// optionally show a message while the authentication provider initializes.onInitializing: ()=><div>Checking for existing login...</div>,// optionally show a message while the user waits to be redirected to the login page.onRedirecting: ()=><div>Redirecting you to the login page...</div>,// optionally show a message login fails.onError: (error: Error)=><div>{error.message}</div>,// optionally pass parameters to `loginWithRedirect` for example a returnTo locationloginWithRedirectParams: ()=>({state: {returnTo: window.location.href},}),});

Call an API

Call a protected API with an Access Token:

importReact,{useEffect,useState}from"react";import{useAuth}from"@developertown/oidc-provider";constPosts=()=>{const{ getAccessTokenSilently }=useAuth();const[posts,setPosts]=useState(null);useEffect(()=>{(async()=>{try{consttoken=awaitgetAccessTokenSilently();constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[getAccessTokenSilently]);if(!posts){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

Events

// src/index.jsimportReactfrom"react";importReactDOMfrom"react-dom";import{Auth0ProviderasAuthenticationProvider,AppState,}from"@developertown/oidc-provider";importAppfrom"./App";ReactDOM.render(<AuthenticationProviderdomain="YOUR_DOMAIN"clientId="YOUR_CLIENT_ID"redirectUri={window.location.origin}useRefreshTokensonAccessTokenChanged={(accessToken: string)=>{/* Do something with the accessToken*/// dispatch(accessTokenChanged(accessToken))// NOTE: this event may not be needed since getAccessTokenSilently() will always grab the latest access token// or perform a silent refresh to get a fresh one}}onAccessTokenExpiring={()=>{// Let the user know their session is expiring// NOTE: when useRefreshTokens is true accessTokens will be automatically refreshed}}onAccessTokenExpired={()=>{// Let the user know their session has expired// NOTE: when useRefreshTokens is true as long as the silent refresh occurs successfully the token will not expire}}onAccessTokenRefreshError={(error: Error)=>{// Handle errors when silently refreshing access tokens. Only applies when useRefreshTokens is true}}onRedirectCallback={(appState?: AppState)=>{// Perform action after redirecting from the authentication provider// NOTE: if no onRedirectCallback is provided the default behavior iswindow.history.replaceState({},document.title,appState?.returnTo||window.location.pathname);}}><App/></AuthenticationProvider>,document.getElementById("app"));

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

OpenID Connect (OIDC) and OAuth2 protocol support for React Single Page Applications (SPA).

Topics

Resources

Code of conduct

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages