Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ionic background not working with msal interceptor #7365

Closed
2 tasks
cdiazp-sacyr opened this issue Oct 8, 2024 · 6 comments
Closed
2 tasks

Ionic background not working with msal interceptor #7365

cdiazp-sacyr opened this issue Oct 8, 2024 · 6 comments
Labels
b2c Related to Azure B2C library-specific issues bug-unconfirmed A reported bug that needs to be investigated and confirmed msal-angular Related to @azure/msal-angular package msal-browser Related to msal-browser package public-client Issues regarding PublicClientApplications question Customer is asking for a clarification, use case or information.

Comments

@cdiazp-sacyr
Copy link

Core Library

MSAL.js (@azure/msal-browser)

Core Library Version

3.24.0

Wrapper Library

MSAL Angular (@azure/msal-angular)

Wrapper Library Version

3.0.23

Public or Confidential Client?

Public

Description

I'm using Ionic, and when I turn off the screen, the interceptor's http calls stop working, and the reason seems to be because angular-common-http is being used.

We have created a custom interceptor to use capacitorHttp, but the acquireTokenSilent method is still using angular-common-http internally, so it still blocks the call

Is there a way to make acquireTokenSilent use capacitorHttp instead of angular-common-http?

Error Message

No response

MSAL Logs

No response

Network Trace (Preferrably Fiddler)

  • Sent
  • Pending

MSAL Configuration

authConfig: {
    clientId: "clientId",
    tenantId: "tenantId",
    authority:
      "https://login.microsoftonline.com/tenantId",
    knownAuthorities: [""],
    redirectUri: "http://localhost:3000",
    postLogoutRedirectUri: "http://localhost:3000",
    scopes: ["user.read"],
    consentScopes: [
      "user.read",
      "api://url/user_impersonation",
    ],
    protectedResourceMap: [
      [
        "https://url/app.api/api",
        ["api://url/user_impersonation"],
      ],
    ],
  },

Relevant Code Snippets

Token stops renewing

Reproduction Steps

  1. I get the token correctly
  2. I turn off the screen of device
  3. In the background, the token renewal is not called

Expected Behavior

should continue renewing token, but it doesn't

Identity Provider

Azure B2C Custom Policy

Browsers Affected (Select all that apply)

Other

Regression

No response

Source

External (Customer)

@cdiazp-sacyr cdiazp-sacyr added bug-unconfirmed A reported bug that needs to be investigated and confirmed question Customer is asking for a clarification, use case or information. labels Oct 8, 2024
@microsoft-github-policy-service microsoft-github-policy-service bot added the Needs: Attention 👋 Awaiting response from the MSAL.js team label Oct 8, 2024
@github-actions github-actions bot added b2c Related to Azure B2C library-specific issues msal-angular Related to @azure/msal-angular package msal-browser Related to msal-browser package public-client Issues regarding PublicClientApplications labels Oct 8, 2024
@tnorling
Copy link
Collaborator

tnorling commented Oct 8, 2024

You can provide your own implementation of the networkClient on the system options passed into PublicClientApplication. This is what msal-browser uses under the hood for all network requests.

See options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/types/_azure_msal_browser.BrowserSystemOptions.html

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Author Feedback Awaiting response from issue author and removed Needs: Attention 👋 Awaiting response from the MSAL.js team labels Oct 8, 2024
@cdiazp-sacyr
Copy link
Author

You can provide your own implementation of the networkClient on the system options passed into PublicClientApplication. This is what msal-browser uses under the hood for all network requests.

See options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/types/_azure_msal_browser.BrowserSystemOptions.html

Thank you very much for your help!

Now, I have implemented this class for managing requests:

import { INetworkModule, NetworkRequestOptions, NetworkResponse } from '@azure/msal-browser';
import { CapacitorHttp } from '@capacitor/core';

export class CustomHttpClient implements INetworkModule {
    
    async sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions, cancellationToken?: number): Promise<NetworkResponse<T>> {
        try {

            const response = await CapacitorHttp.get({ url, headers: options?.headers });

            console.log('GET response:', response);

            return {
                body: response.data, 
                headers: response.headers,
                status: response.status
            } as NetworkResponse<T>;
        } catch (error) {
            console.error('GET request error:', error);
            throw error;
        }
    }
    
    async sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<NetworkResponse<T>> {
        try {
            console.log('URL: ', url, options)
            const response = await CapacitorHttp.post({
                url,
                headers: options?.headers,
                data: options?.body,
            });

            console.log('POST response:', response);

            return {
                body: response.data, 
                headers: response.headers,
                status: response.status
            } as NetworkResponse<T>;
        } catch (error) {
            console.error('POST request error:', error);
            throw error;
        }
    }
}

But it returns the following error: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests.

Do you know what i can do?
Thank you very much!

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Attention 👋 Awaiting response from the MSAL.js team and removed Needs: Author Feedback Awaiting response from issue author labels Oct 9, 2024
@tnorling
Copy link
Collaborator

tnorling commented Oct 9, 2024

Your POST request is likely missing the origin header. I'd suggest confirming and, if so, make sure to include it

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Author Feedback Awaiting response from issue author and removed Needs: Attention 👋 Awaiting response from the MSAL.js team labels Oct 9, 2024
@cdiazp-sacyr
Copy link
Author

Now, I add 'Origin' http://localhost:3000' and it works!!
But when I need to renew the token I obtain this error:

Unsafe attempt to initiate navigation for frame with URL 'https://localhost/home?sync=true' from frame with URL 'https://login.microsoftonline.com/...'. The frame attempting navigation of the top-level window is sandboxed, but the flag of 'allow-top-navigation' or 'allow-top-navigation-by-user-activation' is not set.

BrowserAuthError: monitor_window_timeout: Token acquisition in iframe failed due to timeout. For more visit: aka.ms/msaljs/browser-errors

Is it a configuration problem maybe?
Thanks!

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Attention 👋 Awaiting response from the MSAL.js team and removed Needs: Author Feedback Awaiting response from issue author labels Oct 10, 2024
@tnorling
Copy link
Collaborator

Your redirectUri page is attempting a navigation. Recommended best practice for silent/popup calls is to use a blank page that runs no javascript as your redirectUri page to avoid these types of problems. If that's not possible, you'll need to debug your redirectUri page and see if you can locate where it's attempting a redirect or change to the url

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Author Feedback Awaiting response from issue author and removed Needs: Attention 👋 Awaiting response from the MSAL.js team labels Oct 10, 2024
@cdiazp-sacyr
Copy link
Author

cdiazp-sacyr commented Oct 14, 2024

Finally, we have made a custom solution, in which we manually use localstorage to only renew the token after a certain amount of time.
Our problem was that the acquireTokenSilence method was being called many times in a row, and the server denied it after a few calls in a row.
Now we control that manually.

Thank you very much for your help

@microsoft-github-policy-service microsoft-github-policy-service bot removed the Needs: Author Feedback Awaiting response from issue author label Oct 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
b2c Related to Azure B2C library-specific issues bug-unconfirmed A reported bug that needs to be investigated and confirmed msal-angular Related to @azure/msal-angular package msal-browser Related to msal-browser package public-client Issues regarding PublicClientApplications question Customer is asking for a clarification, use case or information.
Projects
None yet
Development

No branches or pull requests

2 participants