title: Securing REST API Calls in SPAs using MSAL.js with Azure Active Directory - How to Pass Authentication Token to Bearer Strategy
body: <p>I am creating a SPA using React and Express. I am trying to include authentication using MSAL.js and have looked at <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa" rel="nofollow noreferrer">Microsoft's tutorials for SPA</a>. I've been able to implement this with React using @msal-react. While this does perform authentication, it does not protect the REST API from access by unauthenticated users.</p>
  <p>I found the <a href="https://github.com/Azure-Samples/active-directory-javascript-nodejs-webapi-v2" rel="nofollow noreferrer">Active Directory Javascript Nodejs Web API</a> that seems to provide a means for protecting the REST API using Passport and the Bearer strategy, but the links showing how to couple this with the client-side seem to be broken.</p>
  <p>I'm not sure how to connect the authentication that is occurring on the client side with REST API. As I understand it, the authentication token has to be passed, but I am not sure how to pass that.</p>
  <p>The server-side sample code has:</p>
  <pre><code>// API endpoint exposed
  app.get(&quot;/api&quot;,
      passport.authenticate('oauth-bearer', {session: false}),
      (req, res) =&gt; {
          console.log('Validated claims: ', req.authInfo);
  
          // Service relies on the name claim.  
          res.status(200).json({
              'name': req.authInfo['name'],
              'issued-by': req.authInfo['iss'],
              'issued-for': req.authInfo['aud'],
              'scope': req.authInfo['scp']
          });
      }
  );
  </code></pre>
  <p>What I tried to do on the client side was to get the account information:</p>
  <pre><code>import {
    useAccount,
    useMsal
  } from &quot;@azure/msal-react&quot;;
  
  ...
  
  const { accounts } = useMsal();
  const account = useAccount(accounts[0] || {});
  </code></pre>
  <p>From looking at <code>account</code> after authenticating, I thought <code>account.idTokenClaims</code> might have what is necessary, but have had no luck.</p>
  <p>I am stuck because I am not sure if I have a fundamental misunderstanding of how the Bearer strategy works, if I am using MSAL or Passport (or both) incorrectly, or if this is a configuration issue. I appreciate the help!</p>