BrowserAuthError: no_account_error: No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the request.

See original GitHub issue

Core Library

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

Core Library Version

2.15.0

Wrapper Library

MSAL React (@azure/msal-react)

Wrapper Library Version

1.0.1

Description

Users are authenticated with Microsoft Azure AD identity provider, it works great but we can’t retrieve user details from MSAL and MS Graph API.

MSAL Configuration

{
    auth: {
        clientId: "***",
        authority: "***",
        redirectUri: "https://***.fr/.auth/login/aad/callback"
    },
    cache: {
        cacheLocation: "sessionStorage",
        storeAuthStateInCookie: false
    }
}

Relevant Code Snippets

// FILE index.js
import {PublicClientApplication} from "@azure/msal-browser";
import {MsalProvider} from "@azure/msal-react";
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

import "./custom.scss";

const msalInstance = new PublicClientApplication(
    {
        auth: {
            clientId: "***",
            authority: "***",
            redirectUri: "https://***.fr/.auth/login/aad/callback"
        },
        cache: {
            cacheLocation: "sessionStorage",
            storeAuthStateInCookie: false
        }
    }
);

ReactDOM.render(
    <React.StrictMode>
        <MsalProvider instance={msalInstance}>
            <App/>
        </MsalProvider>
    </React.StrictMode>,
    // eslint-disable-next-line no-undef
    document.getElementById("root")
);

// FILE Header.js
import {InteractionRequiredAuthError, InteractionStatus} from "@azure/msal-browser";
import {useMsal} from "@azure/msal-react";
import {faIgloo, faPencilRuler, faSearch, faStethoscope, faUserAstronaut, faWrench} from "@fortawesome/free-solid-svg-icons";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import React, {useEffect, useState} from "react";
import {Button, Form, FormControl, InputGroup, Nav, Navbar, NavDropdown} from "react-bootstrap";

import {useHistory} from "react-router-dom";
import Brand from "../../assets/img/logo.png";

const graphConfig = {
    endpointUserRead: "https://graph.microsoft.com/User.Read"
};

function Header() {
    const [search, setSearch] = useState("");
    const history = useHistory();

    const {instance, inProgress, accounts} = useMsal();
    const [apiData, setApiData] = useState(null);

    useEffect(() => {
        const accessTokenRequest = {
            scopes: ["user.read"],
            account: accounts[0]
        };

        if (!apiData && inProgress === InteractionStatus.None) {
            instance.acquireTokenSilent(accessTokenRequest)
                    .then((accessTokenResponse) => {
                        let accessToken = accessTokenResponse.accessToken;
                        callMsGraph(accessToken, graphConfig.endpointUserRead)
                            .then((response) => {
                                setApiData(response);
                            });
                    })
                    .catch((error) => {
                        if (error instanceof InteractionRequiredAuthError) {
                            instance.acquireTokenRedirect(accessTokenRequest);
                        }
                        console.log(error);
                    });
        }
    }, [instance, accounts, inProgress, apiData]);

    return (
        <div className="sticky-top" style={{backgroundColor: "#000a64"}}>
            <Navbar variant="dark" style={{height: 90, marginBottom: 50}}>
                <Navbar.Brand>
                    <Nav.Link href="/">
                        <img src={Brand} height="100" alt="TF1 Brand"/>
                    </Nav.Link>
                </Navbar.Brand>
                <Navbar.Toggle aria-controls="basic-navbar-nav"/>
                <Navbar.Collapse id="basic-navbar-nav">
                    <Nav className="mr-auto">
                        <Nav.Link href="/" className="text-center">
                            <span style={{fontSize: 30}}><FontAwesomeIcon icon={faIgloo}/></span>
                            <h6>HOME</h6>
                        </Nav.Link>
                        &ensp;
                        <Nav.Link href="/recommendations/rules" className="text-center">
                            <span style={{fontSize: 30}}><FontAwesomeIcon icon={faPencilRuler}/></span>
                            <h6>RULES</h6>
                        </Nav.Link>
                        &ensp;
                        <NavDropdown className="text-center bs-popover-auto" title={<div style={{height: 55}}><span style={{fontSize: 30}}>
                                                                                        <FontAwesomeIcon icon={faStethoscope}/>
                                                                                        <h6>AUDIT</h6>
                                                                                    </span></div>} id="basic-nav-dropdown">
                            <NavDropdown.Item href="/audit/azure/blobs">Blob</NavDropdown.Item>
                            <NavDropdown.Item href="/audit/cassandra/tables">Cassandra</NavDropdown.Item>
                            <NavDropdown.Item href="/audit/snowflake/tables">Snowflake</NavDropdown.Item>
                            <NavDropdown.Item href="/audit/sqlserver/tables">SQL Server</NavDropdown.Item>
                            <NavDropdown.Item href="/audit/metadata/parameters">Metadata</NavDropdown.Item>
                        </NavDropdown>
                        &ensp;
                        <Nav.Link href="/other" className="text-center">
                            <span style={{fontSize: 30}}><FontAwesomeIcon icon={faWrench}/></span>
                            <h6>OTHER</h6>
                        </Nav.Link>
                    </Nav>
                </Navbar.Collapse>
                &ensp;
                <Form inline onSubmit={() => history.push("/search/" + search)}>
                    <InputGroup className="flex-nowrap">
                        <FormControl type="text" placeholder="Search ..." className="mr-sm-auto" value={search} onChange={(event) => {
                            setSearch(event.target.value);
                        }}/>
                        <InputGroup.Append>
                            <Button type="submit" variant="light"><span><FontAwesomeIcon icon={faSearch}/></span></Button>
                        </InputGroup.Append>
                    </InputGroup>
                </Form>
                &emsp;
                <span style={{fontSize: 30, color: "white"}} onClick={() => history.push("/user")} className="text-center">
                    <FontAwesomeIcon icon={faUserAstronaut}/>
                </span>
            </Navbar>
        </div>
    );
}

async function callMsGraph(accessToken, endpoint) {
    const headers = new Headers();
    const bearer = `Bearer ${accessToken}`;

    headers.append("Authorization", bearer);

    const options = {
        method: "GET",
        headers: headers
    };

    return fetch(endpoint, options).then(response => response.json())
                                   .catch(error => console.log(error));
}

export default Header;

Identity Provider

Azure AD / MSA

Source

External (Customer)

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
cbismuthcommented, Jul 9, 2021

Problem solved, everything is contained is the response below, thanks a lot @derisen:

    axios.get("/.auth/me")
         .then(response => {
             console.log(response.data);
         })
         .catch(error => console.log(error));
0reactions
cbismuthcommented, Jul 9, 2021

I’ll read this, thanks @derisen, and I’ll post the solution in the comments.

Read more comments on GitHub >

github_iconTop Results From Across the Web

MSAL in Angular - no_account_error: No account object ...
... No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account ...
Read more >
microsoft-authentication-library-for-js/BrowserAuthError.ts at dev ...
desc: "No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the ......
Read more >
AzureAD/microsoft-authentication-library-for-js | Job 2
desc: "No account object provided to acquireTokenSilent and no active ... Please call setActiveAccount or provide an account on the request.
Read more >
@azure/msal-browser | microsoft-authentication-libraries-for-js
If set, MSAL stores the auth request state required for validation of the auth flows in the browser ... account - Account object...
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