question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot login on msal-react, error on console.log()

See original GitHub issue

Core Library

MSAL.js v2 (@azure/msal-browser)

Core Library Version

^2.14.2

Wrapper Library

MSAL React (@azure/msal-react)

Wrapper Library Version

MSAL.js for React B2C Sample

Description

I am getting an error in the console.log() FetchClient.ts:24 as the place for the error. Line 24 is the await in the function below /** * Fetch Client for REST endpoints - Get request * @param url * @param headers * @param body */ async sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<NetworkResponse<T>> { let response; try { response = await fetch(url, { method: HTTP_REQUEST_TYPE.GET, headers: this.getFetchHeaders(options) }); } catch (e) { if (window.navigator.onLine) { throw BrowserAuthError.createGetRequestFailedError(e, url); } else { throw BrowserAuthError.createNoNetworkConnectivityError(); } }

Error Message

The resulting error from the console.log();

GET https://promise%20ltd.b2clogin.com/promise%20ltd.onmicrosoft.com/b2c_1_signin_signout/v2.0/.well-known/openid-configuration net::ERR_NAME_NOT_RESOLVED

Msal Logs

not sure

MSAL Configuration

// Config object to be passed to Msal on creation
export const msalConfig = {
    auth: {
        clientId: "3a68f70e-c7c9-4115-9b55-7bf1da0d366f",
        authority: "https://Promise Ltd.b2clogin.com/Promise Ltd.onmicrosoft.com/B2C_1_signin_signout",
        knownAuthorities: ["Promise Ltd.b2clogin.com"],
        redirectUri: "http://localhost:4200",
        postLogoutRedirectUri: "http://localhost:4200"
    }
};

// Scopes you add here will be prompted for consent during login
export const loginRequest = {
    scopes: ["https://Promise Ltd.onmicrosoft.com/helloapi/demo.read"]
};

Relevant Code Snippets

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */

import { INetworkModule, NetworkRequestOptions, NetworkResponse } from "@azure/msal-common";
import { BrowserAuthError } from "../error/BrowserAuthError";
import { HTTP_REQUEST_TYPE } from "../utils/BrowserConstants";

/**
 * This class implements the Fetch API for GET and POST requests. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
 */
export class FetchClient implements INetworkModule {

    /**
     * Fetch Client for REST endpoints - Get request
     * @param url 
     * @param headers 
     * @param body 
     */
    async sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<NetworkResponse<T>> {
        let response;
        try {
            response = await fetch(url, {
                method: HTTP_REQUEST_TYPE.GET,
                headers: this.getFetchHeaders(options)
            });
        } catch (e) {
            if (window.navigator.onLine) {
                throw BrowserAuthError.createGetRequestFailedError(e, url);
            } else {
                throw BrowserAuthError.createNoNetworkConnectivityError();
            }
        }

        try {
            return {
                headers: this.getHeaderDict(response.headers),
                body: await response.json() as T,
                status: response.status
            };
        } catch (e) {
            throw BrowserAuthError.createFailedToParseNetworkResponseError(url);
        }
    }

    /**
     * Fetch Client for REST endpoints - Post request
     * @param url 
     * @param headers 
     * @param body 
     */
    async sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<NetworkResponse<T>> {
        const reqBody = (options && options.body) || "";

        let response;
        try {
            response = await fetch(url, {
                method: HTTP_REQUEST_TYPE.POST,
                headers: this.getFetchHeaders(options),
                body: reqBody
            });
        } catch (e) {
            if (window.navigator.onLine) {
                throw BrowserAuthError.createPostRequestFailedError(e, url);
            } else {
                throw BrowserAuthError.createNoNetworkConnectivityError();
            }
        }

        try {
            return {
                headers: this.getHeaderDict(response.headers),
                body: await response.json() as T,
                status: response.status
            };
        } catch (e) {
            throw BrowserAuthError.createFailedToParseNetworkResponseError(url);
        }
    }

    /**
     * Get Fetch API Headers object from string map
     * @param inputHeaders 
     */
    private getFetchHeaders(options?: NetworkRequestOptions): Headers {
        const headers = new Headers();
        if (!(options && options.headers)) {
            return headers;
        }
        const optionsHeaders = options.headers;
        Object.keys(optionsHeaders).forEach((key) => {
            headers.append(key, optionsHeaders[key]);
        });
        return headers;
    }

FetchClient.ts 
-----------------------

    private getHeaderDict(headers: Headers): Record<string, string> {
        const headerDict: Record<string, string> = {};
        headers.forEach((value: string, key: string) => {
            headerDict[key] = value;
        });
        return headerDict;
    }
}

Reproduction Steps

https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-react-samples/b2c-sample

Expected Behavior

this error is not supposed to show

Identity Provider

Azure B2C Basic Policy

Browsers Affected (Select all that apply)

Internet Explorer

Regression

none

Source

Internal (Microsoft)

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:18 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
hectormmgcommented, Feb 15, 2022

@getwebem yes, I’m suggesting you add the system configuration object to your config to turn the MSAL logger on. This way you’ll be able to see the logs on the browser console and get more diagnostic info.

0reactions
msftbot[bot]commented, Feb 28, 2022

@getwebem This issue has been automatically marked as stale because it is marked as requiring author feedback but has not had any activity for 5 days. If your issue has been resolved please let us know by closing the issue. If your issue has not been resolved please leave a comment to keep this open. It will be closed automatically in 7 days if it remains stale.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Logging errors and exceptions in MSAL.js - Microsoft Entra
Enable logging in MSAL. js (JavaScript) by passing a loggerOptions object during the configuration for creating a PublicClientApplication ...
Read more >
azure/msal-browser redirect not working correctly. · Issue #2796
This was done using msal-react-samples/typescript-sample. When using loginRedirect() the app is logged in, and returned to the redirect uri, ...
Read more >
Cannot return authenticated account information (using MSAL)
Goal: I want the users to be able to login and sign-up on the app (react) using their personal emails (as consumers) Gmail,...
Read more >
How To Use console.log() in React JS - Upmostly
Take the following React code: function Element() { //Code is OK const variable = 1; console. log('1'); //Bug HERE while (true); console. log('2');...
Read more >
Using MSAL.js to integrate React Single-page ... - YouTube
Enable SSO and get an access token for Microsoft Graph API. ... using MSAL React templates, and acquiring tokens with MSAL React hooks....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found