AxaFrance / oidc-client

Light, Secure, Pure Javascript OIDC (Open ID Connect) Client. We provide also a REACT wrapper (compatible NextJS, etc.).
MIT License
572 stars 151 forks source link

A proper way to read scope and expiresAt #1285

Open pavdev64 opened 4 months ago

pavdev64 commented 4 months ago

I'd like to read scope value from access token and value of expiresAt.

First I tried to get accessTokenPayload using useOidcAccessToken() like this

const { accessToken, accessTokenPayload } = useOidcAccessToken();

but accessTokenPayload was undefined all the time while accessToken had a value.

With version 5.x I used

    const tokens = Oidc.get().tokens;
    const scope = (tokens?.accessTokenPayload?.scope ?? '').split(' ');
    const expiresAt = tokens?.expiresAt ?? undefined;

This worked, until version 6.x where Oidc.get() started to throw an exception. And it isn't mentioned the in breaking changes.

I changed code to use OidcClient.get() instead

    const tokens = OidcClient.get().tokens;
    const scope = (tokens?.accessTokenPayload?.scope ?? '').split(' ');
    const expiresAt = tokens?.expiresAt ?? undefined;

but still wondering if this is a correct way if we have hooks and actually why useOidcAccessToken() returns accessTokenPayload with undefined value.

Is this a proper way how to do that?

guillaume-chervet commented 4 months ago

hi @pavdev64 , Thank you for you issue.

undefined is not a normal behavior. Do you have an error in your console?

guillaume-chervet commented 4 months ago

What happen if you set up your configuration on this repository demo @pavdev64 ?

pavdev64 commented 4 months ago

I tested that. The accessTokenPayload is null. It seems to be correct. The scope is actually a property of tokens. However the scope is missing in the tokens type.

export type Tokens = {
    refreshToken: string;
    idTokenPayload:any;
    idToken:string;
    accessTokenPayload:any;
    accessToken:string;
    expiresAt: number;
    issuedAt: number;
};

so I had to retype it to any. This works for me:

    const tokens = OidcClient.get().tokens;
    const scope = ((tokens as any)?.scope ?? '').split(' ');
    const expiresAt = tokens?.expiresAt ?? undefined;

The scope is present here.