Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking MSAL sign in from static HTML page

I'm using Azure AD B2C to manage authentication in my ReactJs SPA app and the MSAL.js library to manage jwt tokens, authentication, etc. which works nicely.

I also have a static HTML page that sits in front of the SPA app but not a part of it. This HTML page is just a nicely designed landing page for general public and it must exist for marketing purposes.

I need to invoke MSAL sign in from this HTML page so that I have a nice and smooth login experience. Currently, the login button on the HTML page simply redirects the user to a protected area in my ReactJs app. When the user hits the SPA app which is protected, MSAL kicks in and automatically redirects the user to Azure AD B2C login page which works fine but the experience is ugly. That's why I want to invoke the sign in process from the HTML page. I could use some help with this.

Here's what I've done so far:

First, I created a reference to MSAL.js in the HTML page using the following:

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/0.1.3/js/msal.min.js"></script>

I then added a <script> section within the HTML page to add the necessary Azure AD B2C tenant info. These are the same parameters I'm using in the ReactJs app:

<script>
   var instance = 'https://login.microsoftonline.com/tfp/';
   var tenant = 'myazureadb2ctenant.onmicrosoft.com';
   var signInPolicy = 'B2C_1_SignUp_SignIn';
   var applicationId = 'my-application-id';
   var scopes = ['https://myazureadb2ctenant.onmicrosoft.com/webclient/readaccess'];
   var redirectUri = 'https://example.com/member';

   // My function to redirect user to Azure AD B2C sign in/sign up page
   var mySignInFunction() {

       // What's next here?
   };

</script>

I think the last step will be to add an onClick() function to the button on my HTML page.

<button onClick="mySignInFunction()">Click here to login</button>

I'd appreciate some help in filling in the blanks here, in particular the sign in function.

like image 543
Sam Avatar asked Jun 04 '18 15:06

Sam


1 Answers

Outside the mySignInFunction function, you create an Msal.UserAgentApplication instance:

var authority = `${instance}${tenant}/${signInPolicy}`;

var clientApplication = new Msal.UserAgentApplication(
  applicationId,
  authority,
  function (errorDescription, token, error, tokenType) {
    // Called if error has occurred.
  },
  {
    redirectUri: redirectUri
  });

Inside the mySignInFunction function, you then invoke the Msal.UserAgentApplication.loginRedirect function:

clientApplication.loginRedirect(scopes);
like image 116
Chris Padgett Avatar answered Sep 22 '22 00:09

Chris Padgett