0

J'ai un problème avec get token lorsque je me connecte avec Azure Active Directory à l'aide de msal.js.Impossible d'obtenir un jeton lors de la connexion avec Azure Active Directory à l'aide de msal.js

Peut-être que je vais vous décrire comment l'application fonctionne dans plusieurs situations.

I. La connexion automatique avec l'authentification Active Directory est désactivée. Le rappel sur le portail d'enregistrement des applications est défini sur page d'accueil de l'application. J'ai utilisé le code de https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/devApps/VanillaJSTestApp/index_LoginPopup.html

  1. Entrez l'application sans autorisation
  2. Cliquez sur le bouton qui fonctionne loginPopup, après log in jeton get.

Tout fonctionne, mais je veux l'autorisation avec l'authentification Active Directory

II. La connexion automatique avec l'authentification Active Directory est activée. Le rappel sur le portail d'enregistrement des applications est défini sur "***. Auth/login/aad/callback". J'ai utilisé le code de https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/devApps/VanillaJSTestApp/index_LoginPopup.html

  1. Entrez l'application avec l'autorisation et connectez-vous avec l'authentification Active Directory
  2. acquireTokenSilent envoie erreur comme « user_login_error: Connexion utilisateur est nécessaire ».
  3. Cliquez sur le bouton qui fonctionne loginPopup, après log in je reçois erreur comme « L'adresse de réponse **** ne correspond pas aux adresses de réponse configurées pour l'application »

MISE À JOUR: Après userAgentApplication set. redirectUri = '**** /. auth/login/aad/callback' et lancez loginPopup, le token est livré, mais il est toujours double.

En résumé, après la connexion avec Azure, j'obtiens une erreur de acquireTokenSilent " user_login_error: La connexion de l'utilisateur est requise ".

III. Je voudrais l'application se comporte comme suit:

  1. Entrez l'application avec l'autorisation et connectez-vous avec l'authentification Active Directory
  2. Get jeton

Puis-je le faire comme ça?

+0

« L'adresse de réponse **** ne correspond pas aux adresses de réponse configurées pour l'application ». Cette erreur implique qu'il y a un problème avec la configuration de votre application. Assurez-vous que votre URL de réponse est correcte. Pouvez-vous partager les détails dans la configuration de votre application et l'erreur exacte que vous obtenez? –

+0

Cette erreur s'affiche car l'URL de réponse est définie sur Azure Active Directory ("/.auth/login/aad/callback") que je souhaite utiliser pour autoriser. Lorsque l'URL de réponse est définie sur l'application de page d'accueil, loginPopup fonctionne, mais je ne le souhaite pas. Je veux un jeton après la connexion avec l'authentification Active Directory. – tmszyman

+0

Vous devez vous assurer que l'URL de réponse que vous souhaitez utiliser est ** également ** définie correctement dans l'enregistrement de l'application. Il semble que vous ayez configuré votre page d'accueil lors de l'enregistrement de votre application, mais pas votre point de terminaison de rappel. –

Répondre

0

Vous mélangeaient Easy Auth et protéger le site manuellement à l'aide MSAL.

Si vous souhaitez que la page contextuelle pour la connexion avec la fenêtre contextuelle Azure Active Directory soit automatiquement, vous pouvez modifier la source pour ajouter la fonction permettant d'exécuter la méthode loginPopup() lorsque le document est complètement chargé.Voici un exemple de code pour votre référence:

<html> 
<head> 
    <title>authentication with Msal.js app</title> 
    <style> 
     .hidden { 
      visibility: hidden 
     } 

     .visible { 
      visibility: visible 
     } 
    </style> 
</head> 
<body> 
    <!-- bluebird only needed if this page needs to run on Internet Explorer --> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js" class="pre"></script> 
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/0.1.1/js/msal.min.js"></script> 
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" class="pre"></script> 

    <h1>Sending an email with msal.js and Microsoft Graph</h1> 
    <div> 
     <div id="label">Sign-in with Microsoft</div> 
     <button id="auth" onclick="loginPopup();">Login (with Popup)</button> 
    </div> 
    <div id="sendEmail" class="hidden"> 
     <input id="emailToSendTo" type="text" /> 
     <button id="auth" onclick="sendEmail();">Send email</button> 
    </div> 

    <pre class="response"></pre> 

    <script class="pre"> 
     var applicationConfig = { 
      clientID: '1e6af2ed-686c-4914-96ed-0cd7b1673cbb', 
      graphEndpoint: "https://graph.microsoft.com/v1.0/me/sendMail", 
      graphScopes: ["user.read", "mail.send"] 
     }; 
    </script> 

    <script> 
     var userAgentApplication = new Msal.UserAgentApplication(applicationConfig.clientID, applicationConfig.authority, authCallback); 
     function authCallback(errorDesc, token, error, tokenType) { 
      //This function is called after loginRedirect. msal object is bound to the window object after the constructor is called. 
      if (token) { 
      } 
      else { 
       log(error + ":" + errorDesc); 
      } 
     } 

     function loginPopup() { 
      userAgentApplication.loginPopup(applicationConfig.graphScopes).then(function (idToken) { 
       //Login Success 
       userAgentApplication.acquireTokenSilent(applicationConfig.graphScopes).then(function (accessToken) { 
        //AcquireToken Success 
        updateUI(); 
       }, function (error) { 
        //AcquireToken Failure, send an interactive request. 
        userAgentApplication.acquireTokenPopup(applicationConfig.graphScopes).then(function (accessToken) { 
         updateUI(); 
        }, function (error) { 
         console.log(error); 
        }); 
       }) 
      }, function (error) { 
       console.log(error); 
      }); 

     } 

     function updateUI() { 
      var authButton = document.getElementById('auth'); 
      authButton.innerHTML = 'logout'; 
      authButton.setAttribute('onclick', 'logout();'); 
      var label = document.getElementById('label'); 
      label.innerText = "Hello " + userAgentApplication.getUser().name + "! Please send an email with Microsoft Graph"; 

      // Show the email address part 
      var sendEmailSpan = document.getElementById('sendEmail'); 
      sendEmailSpan.className = "visible"; 
      var emailAddress = document.getElementById('emailToSendTo'); 
      emailAddress.value = userAgentApplication.getUser().displayableId; 
     } 

     function logout() { 
      // Removes all sessions, need to call AAD endpoint to do full logout 
      userAgentApplication.logout(); 
     } 

     function sendEmail() { 
      userAgentApplication.acquireTokenSilent(applicationConfig.graphScopes) 
       .then(function (token, error) { 
        $.ajax({ 
         type: "POST", 
         contentType: "application/json", 
         dataType: 'json', 
         beforeSend: function (request) { 
          request.setRequestHeader('Authorization', 'bearer ' + token); 
         }, 
         url: applicationConfig.graphEndpoint, 
         data: JSON.stringify({ 'message': getEmail(), 'saveToSentItems': true }), 
         processData: false, 
         success: function (msg) { 
          log('Mail sucessfully sent.'); 
         }, 
         statusCode: { 
          200: function() { 
           log('Mail sucessfully sent.'); 
          }, 
          202: function() { 
           log('Mail sucessfully sent.'); 
          } 

         } 
        }); 
       }); 
     } 

     function log(s) { 
      document.body.querySelector('.response').appendChild(document.createTextNode("\n\n" + JSON.stringify(s, true, 2))); 
     } 

     function getEmail() { 
      var email = { 
       Subject: 'Welcome to Microsoft Graph development with Msal and the Microsoft Graph sample', 
       Body: { 
        ContentType: 'HTML', 
        Content: getEmailContent() 
       }, 
       ToRecipients: [ 
        { 
         EmailAddress: { 
          Address: userAgentApplication.getUser().displayableId 
         } 
        } 
       ] 
      }; 
      return email; 
     } 

     // Get the HTMl for the email to send. 
     function getEmailContent() { 
      return "<html><head> <meta http-equiv=\'Content-Type\' content=\'text/html; charset=us-ascii\'> <title></title> </head><body style=\'font-family:calibri\'> <p>Congratulations " + userAgentApplication.getUser().name + ",</p> <p>This is a message from the Microsoft Graph Connect sample. You are well on your way to incorporating Microsoft Graph endpoints in your apps. </p> <h3>What&#8217;s next?</h3><ul><li>Check out <a href='https://graph.microsoft.io' target='_blank'>graph.microsoft.io</a> to start building Microsoft Graph apps today with all the latest tools, templates, and guidance to get started quickly.</li><li>Use the <a href='https://graph.microsoft.io/graph-explorer' target='_blank'>Graph explorer</a> to explore the rest of the APIs and start your testing.</li><li>Browse other <a href='https://github.com/microsoftgraph/' target='_blank'>samples on GitHub</a> to see more of the APIs in action.</li></ul> <h3>Give us feedback</h3> <ul><li>If you have any trouble running this sample, please <a href='https://github.com/microsoftgraph/angular-connect-rest-sample/issues' target='_blank'>log an issue</a>.</li><li>For general questions about the Microsoft Graph API, post to <a href='https://stackoverflow.com/questions/tagged/microsoftgraph?sort=newest' target='blank'>Stack Overflow</a>. Make sure that your questions or comments are tagged with [microsoftgraph].</li></ul><p>Thanks and happy coding!<br>Your Microsoft Graph samples development team</p> <div style=\'text-align:center; font-family:calibri\'> <table style=\'width:100%; font-family:calibri\'> <tbody> <tr> <td><a href=\'https://github.com/microsoftgraph/angular-connect-rest-sample\'>See on GitHub</a> </td> <td><a href=\'https://officespdev.uservoice.com/\'>Suggest on UserVoice</a> </td> <td><a href=\'https://twitter.com/share?text=I%20just%20started%20developing%20%23Angular%20apps%20using%20the%20%23MicrosoftGraph%20Connect%20sample!%20&url=https://github.com/microsoftgraph/angular-connect-rest-sample\'>Share on Twitter</a> </td> </tr> </tbody> </table> </div> </body> </html>"; 
     }; 


     $(document).ready(function() { 
      loginPopup(); 
     }); 
    </script> 
</body> 
</html>