Git Product home page Git Product logo

oidc-react's Introduction

OIDC React

code style: prettier code style: airbnb Commitizen friendly semantic-release Build & Deploy

Language grade: JavaScript codecov Maintainability

oidc-react logo

About

React component (AuthProvider) to provide OpenID Connect and OAuth2 protocol support. Has hooks ๐ŸŽ‰

Based on oidc-client-ts.

Quickstart

Install packages by running:

$ npm install oidc-react

Usage

import { AuthProvider } from 'oidc-react';

const oidcConfig = {
  onSignIn: () => {
    // Redirect?
  },
  authority: 'https://oidc.io/oauth',
  clientId: 'this-is-a-client-id',
  redirectUri: 'https://my-app.com/',
};

const Routes = () => (
  <AuthProvider {...oidcConfig}>
    <Switch>
      <Route exact path="/">
        <Dashboard />
      </Route>
      ...
    </Switch>
  </AuthProvider>
);

Documentation

Apart from this README, you can find details and examples of using the SDK in the following places:

Contribute & Disclaimer

We love to get help ๐Ÿ™ Read more about how to get started in CONTRIBUTING ๐ŸŒณ

oidc-react's People

Contributors

astahmer avatar bjerk-bot avatar braaar avatar dannyheard7 avatar dependabot-preview[bot] avatar dependabot[bot] avatar ed-sparkes avatar freefrags avatar github-actions[bot] avatar hmvp avatar hwo-wd avatar jamesdh avatar lclc98 avatar lucaskuratani avatar m-irc-o avatar marcuses101 avatar maxinger15 avatar mindplay-dk avatar narmdo avatar pamapa avatar peterhueer94 avatar powersource avatar pseudoramble avatar renovate[bot] avatar ryancole avatar semantic-release-bot avatar simenandre avatar thedome avatar uzunov-stefan avatar zemadz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

oidc-react's Issues

Internet Explorer 11 Support

I noticed while trying to use it in IE11 I'm hitting issues. In particular, the build includes arrow-functions which IE11 does not support at all.

Debugger:
image

So, more of a general question - what browsers does the library attempt to support? I might be one of the last people on planet earth considering supporting IE11 at this point, so I would completely get it if oidc-react does not support it. But it would be good to lay that out clearly. If it does try and support IE11, there may be a babel preset needed to cover this.

Open popup ?

Hello ! Congrats for this start on a React port of oidc-client-js, it's a pretty good job already.

Any way to leverage the impressive set of options of oidc-client-js ? Like opening a popup ?

And also : are you open to PR ?

Cheers, thank you for this lib !

how to get access_token along with id_token from azure ad

Hi Team, I am trying to integrate my react app with Azure AD. I need both id_token and access_token from Azure response.
I found in documentation that to get access_token as well, we need to pass resource identifier in the OAuth request, so I am passing extraQueryParams{resource:"...."} but it seems oidc-react not passing it to oidc-client, please let me know how to pass extraQueryParams and how to get access_token

here is the sample what i am doing.
const oidcConfig = {
authority: 'XXXXXXXXX',
clientId:
'XXXXXXXXXXXXXXX',
responseType: 'id_token token',
redirectUri:'XXXXXXXXXXXXXX',
scope: 'openid',
extraQueryParams: {resource:'XXXXXXXXXXXXXXXXXXXXX'}
};

<AuthProvider {...oidcConfig} onSignIn={this.checkLogin}>

Re-export oidc-client's User type

Can we adjust the code so that the oidc-react package re-exports the User type from oidc-client-js? It'd be helpful for function parameter typing. Thanks.

Fix `typedoc`

After upgrading to >0.20.0 typedoc has stopped working; and our documentation is outdated.

This issue is open for anyone who wants to help out! ๐Ÿ™

Can not use signinSIlent Method with this package

As I saw and tried, this package only supports signRedirect. Here:

await userManager.signinRedirectCallback();

Because of this effect, I can not use signinSilent and querySessionStatus which depends on it. It will throw frame window timeout. But, when I tried to call signinSilentCallback on callback page, it always thowrs no matching state found, because getUser always run first before the signinSilentCallback.

Changing the signinRedirectCallback to signinCallback will fix the issue as this method can decide which sign in method is used.
https://github.com/IdentityModel/oidc-client-js/blob/fe2d2865ebf638a4224d1d3ac8102eb5c006dd01/src/UserManager.js#L288

change default value of autoSignIn

export const AuthProvider: FC<AuthProviderProps> = ({
  children,
  autoSignIn = true,

autoSignIn is a nice feature, but i am not sure if we should turn this on by default. It magically signs in, i first was very surprised how this would work reliable.

Its a feature and oidc-react can also used without the autoSignIn, so lets not enable it by default....

Next.js/SSR compatability

Hi!

I'm implementing OIDC in a next.js project, but since this library uses window.location, I'm getting a window is not defined error on the initial server-side render.

I'm thinking adding something like

if (typeof window === 'undefined') return children;

in AuthProvider, and do nothing auth wise on the server-side render, and just let that happen in the subsequent client side render instead. Do you see any downsides with this, or a better solution, maybe something that would actually make it work server-side?

Using web browser Refresh

We have setup our application to use odic-react and everything works except for one thing.

When we have have signed in to the application and then presses the Refresh button we are
redirected to our landing page for login.
On the landing page we have concluded:

  • We can see that the session storage still contains the oidc information
  • We can use auth.userManager.getData() and retrieve the user
  • auth.userData is null

Because of this, that auth.userData is null, our application assumes that the user is not authenticated.

Can we do anything to force reload of the userdata from the session storage?
Is there any other way of solving this problem?
We could of course make a new sign in, by doing auth.userManager.signinRedirect(),
but it would be nicer to get the information from the session storage and save time.

feat: add skipSigninCallback

  • add new flag: skipSigninCallback
  • improve auth parameter detection code
  • avoid re-declare official Location interface

Question: Defer login until user click button if no active session

Hi,

Is there a simple way to defer the authorize login flow until user clicks a button if there is no active session?

So if there is an active session then load the user profile but if not then show a login button and then auth.signOn() on button click. I have this working if i log out and then log back in without reloading the page but would like the option when user first navigates the page to give them some info and a login button rather than redirect to identity provider for credentials

Thanks, Ed

Feature request: Add a withAuth function similar to withRouter

See https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md and https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/withRouter.js

For all the people who are using class based components

Possible implementation based on https://github.com/pbeshai/use-query-params/blob/master/src/withQueryParams.tsx

type Diff<T, K> = Omit<T, keyof K>;

/**
 * A public higher-order component to access the imperative API
 */
function withAuth<P extends AuthContextProps>(Component: React.ComponentType<P>) {
    const displayName = `withAuth(${Component.displayName || Component.name})`;
    const C: React.FC<Diff<P, AuthContextProps>> = props => {
        const auth = useAuth();

        return (
            <AuthContext.Consumer>
                {context => {
                    return <Component {...(props as P)} {...auth} />;
                }}
            </AuthContext.Consumer>
        );
    };

    C.displayName = displayName;

    return C;
}

Please help, my app isn't being called back after signOut because of AuthContext

Hi, I've never made a request here so please forgive me if this is not the correct way to submit an issue or ask for help. I have a new job that is requiring me to include oauth/identity functionality on a new react app (which I'm trying to learn also). I've decided to use your library since it looked straightforward for my needs. After several days of working with it, I realized today that my post_logout_redirect_uri setting is being ignored. I tracked it down after I looked at the code in your AuthContext.tsx file-in particular when it instantiates a UserManager, using the following code:

export const initUserManager = (props: AuthProviderProps): UserManager => {
  if (props.userManager) return props.userManager;
  const {
    authority,
    clientId,
    clientSecret,
    redirectUri,
    responseType,
    scope,
    automaticSilentRenew,
  } = props;
  return new UserManager({
    authority,
    client_id: clientId,
    client_secret: clientSecret,
    redirect_uri: redirectUri,
    silent_redirect_uri: redirectUri,
    post_logout_redirect_uri: redirectUri,
    response_type: responseType || 'code',
    scope: scope || 'openid',
    loadUserInfo: true,
    automaticSilentRenew,
  });
};

It only accepts authority,
clientId,
clientSecret,
redirectUri,
responseType,
scope,
automaticSilentRenew

Is there a good reason for this, because the userManager settings object is supposed to take many more params, including the post logout redirect uri. Is this designed on purpose to have the redirect_uri and post_logout_redirect_ui always be the same endpoint?

Or maybe I just don't understand, maybe there's a simple workaround so my app works with this lib. The useAuth hook is all over my components so I'm eager to see if this can be fixed.

Maybe there's a perfectly reasonable answer to it (hopefully). And if so I will be grateful for direction.

Thank you for any input or advice.

Thanks

Improve callback functionality

Currently, our context looks for a few parts in the URL (either # or ?). I don't think this is the ultimate solution for handling callback, and I do see some having experience caused by the way we do it (such as #307).

Any thoughts on how we can improve it?

cc: @ryancole

Any plans for SSR support?

This looks like a really neat, simply library but it would appear not to support SSR.

Are there any plans to change that? Would it be a lot of work to implement?

userManager.signinCallback() is called for a logged in user causing uncaught exception

When the user is already logged in but the URL contains the 'code' parameter, oidc-react raises an "No matching state found in storage" exception.

This is because the userManager.signinCallback is always called if there is a 'code' in the URL even though it shouldn't if the user is already logged in (as the state seems to be removed at this time).

The code is at https://github.com/bjerkio/oidc-react/blob/master/src/AuthContext.tsx#L87

I've seen this in my application with the most recent oidc-react and using Google Chrome but it is easy to reproduce using the online demo for oidc-react:

  1. Visit the demo application: https://cobraz.github.io/example-oidc-react/
  2. Log in
  3. When the popup appears saying you're logged in then do not close it(!) but copy the URL from the address bar (should be something like: https://cobraz.github.io/example-oidc-react/#state=3718c8c9ff504d89b98d06108753d414&id_token=xyz.xyz&authuser=0&prompt=none)
  4. Open the new browser tab and paste the URL copied in 3.
  5. Check the console for errors

There should be an exception shown:
Uncaught (in promise) Error: No matching state found in storage

Silent token refresh doesn't seem to actually update the token

So I've been doing a bunch of debugging. In my app it currently looks like:

  1. The access token is e.g. "tokenabcd"
  2. The user can do actions that require authentication.
  3. The access token is refreshed (supposedly) successfully according to logging.
  4. The token is still "tokenabcd"
  5. The user can sometimes still do actions that require authentication, but after a bit my backend (just checking that the jwt isn't expired and all that) starts complaining that the user isn't authenticated.
  6. Refresh the page (f5), now you have a new token "tokendcba", and actions that require authentication work again.

Signout Option

Hello!

I succesfully implemented login option as below. Thanks for such a useful library. But I could not find any information for the logout option in the documents. How can i implement logout option for the following use.

const oidcConfig = {
    onSignIn: (user) => {
        console.log(user);
    },
    authority: 'https://myauthority',
    clientId: 'myclient',
    redirectUri: 'http://localhost:3000/sth',
};

...

<AuthProvider {...oidcConfig}>
    {renderMyForm(true)}
</AuthProvider>

Accessing state after signin

I am sending some state with my signin request as wish to access it again once the signin is complete

export const SimpleLogin: React.FC = (): JSX.Element => {
  const auth = useAuth();
  
  return (
    
      <div>
        {auth?.userData && (
         <>{auth?.userData.profile.name || ''}</>
        )}
        {!auth?.userData && (
          <button onClick={() => auth?.signIn({ state: { targetUrl: window.location.pathname } })}>
            Login
          </button>
        )}
      </div>
  );
};

i need to access this state after login so that i can redirect to the correct path in my application, however state is undefined on the User object in the onSignIn event

<AuthProvider
      authority='someAuthority'
      clientId='someclientid'
      automaticSilentRenew
      responseType="code"
      autoSignIn={false}
      onSignIn={(user) => {
        console.log(user.state);
         // user.state is undefined
      }}
      scope="openid profile email "
      redirectUri={window.location.origin}
    >
      <RestOfMyApp />
    </AuthProvider>

How can i get access to the state after signin. I can see that the state is being included in the query paramaters along with the code on the redirect url, but cant work out how to access it, any help would be greatly welcomed

I noticed #36 allows the state to be sent to the authorizer server so presume it is getting through? Bu then not accessible when try to access onSignIn? @johnkors @cobraz any thoughts?

thanks, Ed

Question: How to work around useAuth + "AuthContext cannot be undefined" error in SSR situation

In v1.5.1, there was a change introduced here to check that AuthContext is defined: #576. It's a reasonable change, but it causes an issue for us. We explicitly avoid rendering these components during SSR because there's no window object, and therefore the library won't handle it.

The code is approximately this:

// Near the root component of the app
if (typeof window !== 'undefined') {
  return <AuthProvider {...oidcConfig}>{children}</AuthProvider>
}
return children

This worked because before 1.5.1 useAuth didn't require the AuthContext to be defined. Now that it does require it this won't work anymore. I cannot optionally call useAuth because that will break the rules of hooks and cause errors from React itself.

Any thoughts? I'm happy to adjust my approach to accommodate the change, but I'm not sure what that adjustment would even be.

Page Reload Issue

Hey, just installed this package, and I'm having an issue where the page is refreshed, the user object doesn't seem to be getting fetched from the session.

Effectively doing something like the following and on page refresh, userData doesn't seem to be getting set (or at least triggering a rerender).

Thanks in advance.

import React from 'react';

import { useAuth } from 'oidc-react';

export const AuthButton: React.FC = () => {
  const auth = useAuth();

  if (!auth.userData) {
    return (
      <button onClick={() => auth.signIn()}>log in</button>
    );
  }

  return (
    <button onClick={() => auth.signOut()}>log out</button>
  );
}

Error: Invalid hook call. Using latest React Version

Steps to reproduce

Install a new CRA project
npx create-react-app test-app --template typescript

Install react-oidc
yarn add oidc-react

Create a new react component Routes.tsx file (OIDC Config copied from https://github.com/cobraz/example-oidc-react/blob/master/src/App.tsx) and add <Routes /> to App.tsx

// Routes.tsx 

import React from 'react';
import { AuthProvider } from 'oidc-react';

const oidcConfig = {
    onSignIn: async (user: any) => {
      alert('You just signed in, congratz! Check out the console!');
      console.log(user);
      window.location.hash = '';
    },
    authority: 'https://accounts.google.com',
    clientId:
      '1066073673387-undfdseanu1soilcdprq1p4m8gq8a1iu.apps.googleusercontent.com',
    responseType: 'id_token',
    redirectUri:
      process.env.NODE_ENV === 'development'
        ? 'http://localhost:3000/'
        : 'https://cobraz.github.io/example-oidc-react',
  };
  
export const Routes = () => (
    <AuthProvider {...oidcConfig}>
          <p>OIDC React</p>
    </AuthProvider>
  );

Start the app
yarn start

Expected behaviour

The app should load and I should be redirected to the Google authority page https://accounts.google.com

Actual behaviour

The app does not load instead displaying the error Error: Invalid hook call. (full error below)

Note

If I remove <AuthProvider {...oidcConfig}> from the Routes.tsx file the app loads


Also if I change the react and react-dom version in package.json to

    "react": "^16.13.1",
    "react-dom": "^16.13.1",

run yarn install and yarn start

the app loads and I am redirected to the Google authority page https://accounts.google.com

Full Error

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js:1465)
    at Object.useState (react.development.js:1496)
    at push../node_modules/oidc-react/build/src/AuthContext.js.exports.AuthProvider (AuthContext.js:75)
    at renderWithHooks (react-dom.development.js:14977)
    at mountIndeterminateComponent (react-dom.development.js:17803)
    at beginWork (react-dom.development.js:19041)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
    at invokeGuardedCallback (react-dom.development.js:4056)
    at beginWork$1 (react-dom.development.js:23956)
    at performUnitOfWork (react-dom.development.js:22771)
    at workLoopSync (react-dom.development.js:22699)
    at renderRootSync (react-dom.development.js:22662)
    at performSyncWorkOnRoot (react-dom.development.js:22285)
    at scheduleUpdateOnFiber (react-dom.development.js:21873)
    at updateContainer (react-dom.development.js:25474)
    at react-dom.development.js:26013
    at unbatchedUpdates (react-dom.development.js:22423)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:26012)
    at Object.render (react-dom.development.js:26095)
    at Module../src/index.tsx (index.tsx:7)
    at __webpack_require__ (bootstrap:784)
    at fn (bootstrap:150)
    at Object.1 (serviceWorker.ts:149)
    at __webpack_require__ (bootstrap:784)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1
resolveDispatcher @ react.development.js:1465
useState @ react.development.js:1496
push../node_modules/oidc-react/build/src/AuthContext.js.exports.AuthProvider @ AuthContext.js:75
renderWithHooks @ react-dom.development.js:14977
mountIndeterminateComponent @ react-dom.development.js:17803
beginWork @ react-dom.development.js:19041
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23956
performUnitOfWork @ react-dom.development.js:22771
workLoopSync @ react-dom.development.js:22699
renderRootSync @ react-dom.development.js:22662
performSyncWorkOnRoot @ react-dom.development.js:22285
scheduleUpdateOnFiber @ react-dom.development.js:21873
updateContainer @ react-dom.development.js:25474
(anonymous) @ react-dom.development.js:26013
unbatchedUpdates @ react-dom.development.js:22423
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26012
render @ react-dom.development.js:26095
./src/index.tsx @ index.tsx:7
__webpack_require__ @ bootstrap:784
fn @ bootstrap:150
1 @ serviceWorker.ts:149
__webpack_require__ @ bootstrap:784
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1
index.js:1 The above error occurred in one of your React components:

    at push../node_modules/oidc-react/build/src/AuthContext.js.exports.AuthProvider (http://localhost:3000/static/js/0.chunk.js:11965:5)
    at App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
console.<computed> @ index.js:1
logCapturedError @ react-dom.development.js:20077
update.callback @ react-dom.development.js:20110
callCallback @ react-dom.development.js:12310
commitUpdateQueue @ react-dom.development.js:12331
commitLifeCycles @ react-dom.development.js:20728
commitLayoutEffects @ react-dom.development.js:23418
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23143
unstable_runWithPriority @ scheduler.development.js:646
runWithPriority$1 @ react-dom.development.js:11268
commitRoot @ react-dom.development.js:22982
performSyncWorkOnRoot @ react-dom.development.js:22321
scheduleUpdateOnFiber @ react-dom.development.js:21873
updateContainer @ react-dom.development.js:25474
(anonymous) @ react-dom.development.js:26013
unbatchedUpdates @ react-dom.development.js:22423
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26012
render @ react-dom.development.js:26095
./src/index.tsx @ index.tsx:7
__webpack_require__ @ bootstrap:784
fn @ bootstrap:150
1 @ serviceWorker.ts:149
__webpack_require__ @ bootstrap:784
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1

[Feature Request] Cannot set authorize endpoint state param

Hi,

I see there's a onBeforeSignin function to use for storing data before signing in. In the OIDC standard there's already something for this - the state parameter. RPs set this on requests towards the authorize endpoint.

In oidc.js, this is done via :
mgr.signinRedirect({state:'some data'})
, where some data can be anything you put into it, url-encoded.

The signIn function of the authContext hides this API, though. Could you make the signIn function take an object that can be passed to the signinRedirect method of oidc.js?

awkward loop after login

Hi! Nice library, I was following your examples starting with minimal config:

  const oidcConfig = {
    authority:
      'http://keycloak:8080/auth/realms/master/.well-known/openid-configuration',
    clientId: 'account',
    redirectUri: 'http://localhost:3000/',
  }

Works out of the box, however I'm running into a weird loop: https://imgur.com/a/9YfS50B It eventualy stops after about ten of those and works fine from then on. It's not usable in this state though.

Authenticating against roughly default keycloak instance.

I'm quite sure, I didn't include any obvious ๐Ÿ’ฉ code while implementing this, however I lack skills to further debug what's causing this :(

Unprotected 404 route?

I'm currently implementing a solution that has protected and unprotected routes. That part is working great. I'm trying to implement a catch all 404 page. I'm having difficulty figuring out where to place this. If I place it after the protected routes component, the 404 page gets redirected to my SSO provider.

Is there a way to implement 404 AND have it unprotected?

Improve tests

After #363 and #479 we've lost some test coverage. We should aim to hit 100% again, this issue tracks that!

Implementing oidc-client-js popup features

Hello,
I want to request the addition of the Popup features from the underlaying oidc-client-js.
I came over an usecase where the user has to login in the middle on an process. If I use the loginMethod provided the user gets
redirected and the users state in the react app is lost since the SPA gets closed on redirect.
I saw that the oidc-client-js has methods to login via an popup and hopefully it is possible for you to add an interface to that methods

Thank you,
Max

Edit: Just saw that there is a Issue about it #235

How can we remove some routes from the auth list?

Hi,

I don't want some routes to be authorize. So, i tried something below but in that case 'onSignIn' function is not triggering.

import { AuthProvider } from 'oidc-react';

const oidcConfig = {
  onSignIn: () => {
    // Redirect?
  },
  authority: 'https://demoauth.dev/oauth',
  clientId: 'demo',
  redirectUri: 'http://localhost:3000/'
};

const Routes = () => (
    <Switch>
      <Route exact path="/">
        <Dashboard />
      </Route>
     <AuthProvider {...oidcConfig}>
     <Route exact path="/list-of-sth">
        <Dashboard />
      </Route>
      </AuthProvider>
    </Switch>
);

Could it be that such an error happened because the redirect-uri is not "localhost: 3000/list-of-sth".

"Failed to minify the code from this file" when building with an old react-scripts

So the actual issue here is that my project is using a too old version of react-scripts, see here https://create-react-app.dev/docs/troubleshooting/#npm-run-build-fails-to-minify , because we've previously ejected create-react-app and are therefore using old deps. We want to uneject so we can start using newer versions, but that might not be such a small task.

But considering I probably have thousands of dependencies installed already and they don't have this problem, I thought I might as well ask if there's anything you can do to help here? Is it that you're doing the compile in a /build directory that's weird and tripping it up?

to be executed: node scripts/build.js 
Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file: 

 	./node_modules/oidc-react/build/src/useAuth.js:6 

Read more here: http://bit.ly/2tRViJ9

add AuthState via reducer

something like:

export interface AuthState {
  user?: User;
  isAuthenticated: boolean;
  isLoading: boolean;
  error?: Error;
}

inside the context:

const [state, dispatch] = useReducer(reducer, initialAuthState);

Additionally a AuthReducer.tsx file is handling the reducing. I could put together a merge request, iff wanted.

Read from localstorage when initializing

Hey how have people implemented localStorage so that the auth state is maintained through refreshes?
There several SO Q&As about this. Seems like the solution is to put it within AuthContext rather than a HOC that wraps around your package? Would you agree and would you like a PR for it?

More than one userManager

We have found that we get several instances of the userManager.
It feels that this is not the correct behaviour.
We have made a simple test application with just a button to make a signin.
Simply by browsing to the page we get these messages in the console window:

UserManager.ctor: monitorSession is configured, setting up session monitor
WebStorageStateStore.get user:https://my-host/:{clientId}
UserManager.ctor: monitorSession is configured, setting up session monitor
WebStorageStateStore.get user:https://my-host/:{clientId}
UserManager._loadUser: no user storageString
UserManager._loadUser: no user storageString
UserManager.getUser: user not found in storage
UserManager.getUser: user not found in storage
WebStorageStateStore.get user:https://my-host/:{clientId}
UserManager._loadUser: no user storageString
UserManager.getUser: user not found in storage
UserManager.ctor: monitorSession is configured, setting up session monitor
WebStorageStateStore.get user:https://my-host/:{clientId}
UserManager.ctor: monitorSession is configured, setting up session monitor
WebStorageStateStore.get user:https://my-host/:{clientId}
UserManager._loadUser: no user storageString
UserManager._loadUser: no user storageString
UserManager.getUser: user not found in storage
UserManager.getUser: user not found in storage

Our interpretation of this that we get four instances of the userManager (four .ctor).
Why? Could we do anything wrong?

useAuth returns AuthContextProps | null

I'm new to your library. I was just wondering why the 'useAuth' hook is returning either AuthContextProps or null.

Coming from Auth0 and their useAuth0 hook I was a little bit surprized.

Silent renew doesn't work if window is not focused.

Hello! First of all, thank you for this great library. The best react oidc-client I could find so far.

Regarding the issue, the automaticSilentRenew doesn't work if the window is not focused. So, if you are in a different tab and you try to switch back to the tab of the application after the token is expired, the automaticSilentRenew doesn't work anymore.

It should be great to trigger the automaticSilentRenew on windows focus if the token is not valid anymore.

Weird automatic log in/log out behaviour

This might be two bugs but maybe it's just me doing something wrong. My code for reference https://github.com/Edgeryders-Participio/realities/pull/133/files

  1. If you're in your app logged in and refresh the page (even clearing cache with ctrl-f5) you are still visibly logged in. But if you open the same link in a new tab then you look logged out. Even if you can click Log in and be immediately redirected back to the app without filling in your username/password, since you in fact actually were logged in. This might be related to me setting autoSignIn={false} but that's because I don't want the user automatically redirected to the log in page on visit (it's a SPA, and some users shouldn't have to log in). So I kind of want autoSignIn to be false, but I want detection of already being signed in to be more automatic.

  2. When I call signOut this module's cache mostly seems to be cleared of the log in info. If I click Log in in the app then I'm automatically redirected back to the app since I'm technically still logged in. But I want the option of logging into another account than the one I'm currently logged into.

Any ideas how to fix either of these?

checksession called too many times

I found that the checksession api be called too many times, and found that there are too many UserManager be created, cache userManager in window and avoid the issue

image

Idp SignOut

Hi,

oidc-js calls the endsession endpoint on logout, so the user get's not only logged out at the client, but also the identityprovider. The logout in oidc-react only logs out at the client (removes auth data from session storage).

I could not find a way of doing the full signout at the identityprovider - is there one? Or could you add it? The UserManager. signoutRedirect() in oidc-js will execute the idp signout redirect, I believe.

ref Angular sample

An error in "develop" branch

I've packed "develop" branch with command "npm pack" to make tgz file.
(I need to make some changes in oidc-react)
When using oidc-react as packed tgz in the project "example-oidc-react" (npm install ../oidc-react/oidc-react-1.0.0-alpha.5.tgz)

I've got an error when running in a browser:

Uncaught TypeError: this._signinStart is not a function
    at Object.t [as signIn] (oidc-client.min.js:47)
    at onClick (LoggedIn.tsx:12)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:306)
    at executeDispatch (react-dom.development.js:389)
    at executeDispatchesInOrder (react-dom.development.js:414)
    at executeDispatchesAndRelease (react-dom.development.js:3278)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:3287)
    at forEachAccumulated (react-dom.development.js:3259)
    at runEventsInBatch (react-dom.development.js:3304)
    at runExtractedPluginEventsInBatch (react-dom.development.js:3514)
    at handleTopLevel (react-dom.development.js:3558)
    at batchedEventUpdates$1 (react-dom.development.js:21871)
    at batchedEventUpdates (react-dom.development.js:795)
    at dispatchEventForLegacyPluginEventSystem (react-dom.development.js:3568)
    at attemptToDispatchEvent (react-dom.development.js:4267)
    at dispatchEvent (react-dom.development.js:4189)
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at discreteUpdates$1 (react-dom.development.js:21887)
    at discreteUpdates (react-dom.development.js:806)
    at dispatchDiscreteEvent (react-dom.development.js:4168)
t @ oidc-client.min.js:47
onClick @ LoggedIn.tsx:12
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168
example-oidc-react:1 Unchecked runtime.lastError: The message port closed before a response was received.

When using npm package version 1.0.0-alpha.5 everything is Ok.

I've pulled version 1.0.0-alpha.5 (git checkout tags/v1.0.0-alpha.5 -b v1.0.0-alpha.5-branch)
Packed it tgz. Everything is Ok.

So, version 1.0.0-alpha.5 was Ok, "develop" branch is not Ok.

localhost vs 127.0.0.1 network request differences

Hi, we're having issues where we are getting multiple requests to "open-id configuration" which then get cancelled (looking in network tab in Chrome) when using IP address 127.0.0.1 using our OIDC service locally. If we use localhost it works as expected.

We found this out because when developing locally I had no issues but when deploying we had SSO run on a different server, and when pointing to this I'm getting about 5 times as many requests and sluggish behaviour. Running the same SSO locally, and using localhost works as expected. Switching to the IP address of localhost causes similar behaviour to when it's been accessed via another server.

Could it be explained to me why it's doing this please? I did try adding 127.0.0.1 localhost to hosts file but it made no difference.

But essentially we're seeing if we run the client and SSO locally, it's fine. When SSO is elsewhere or not accessed via localhost we're seeing far more network requests and also re-renders as a result. We're running UserSsoLifetime at NULL and session token for 3600.

Thanks.

Edit: Further reading shows it tries to connect to connect/session, but on localhost this succeeds, on 127.0.0.1 it fails with "login_required", it looks like the cookie isn't being passed. I am, however, still getting token data displayed from authData.

AuthProvider should support every config available on UserManager

AuthProvider should support every config available on UserManager.
Currently it seems support only :

    authority,
    clientId,
    clientSecret,
    redirectUri,
    silentRedirectUri,
    postLogoutRedirectUri,
    responseType,
    scope,
    automaticSilentRenew,
    loadUserInfo,
    popupWindowFeatures,
    popupRedirectUri,
    popupWindowTarget

In initUserManager, you have destructured settings object omitting lot of config properties such as metadata or extraQueryParams which should be support as in oidc-client library.

Trying to get withAuth working

Hi guys,
I am having issues getting the example repo to work with a Class component using withAuth .
Is it possible to add an example of it? Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.