service authenticating against azure ad and EWS












0















I am building a daemon/non-interactive service to use EWS in O365 as a specific user. In order to communicate with EWS over OAUTH2.0 I am trying to properly register the application and authenticate against AAD. Preferably I would like to use certificate based authentication, but I did not get that far.



The code is below (its working):



    static void Main(string args)
{
string tenant = "redacted.onmicrosoft.com";
string authority = "https://login.microsoftonline.com/" + tenant;
string clientId = "44964df2-3333-2222-1111-redcated";
string resource = "https://outlook.office365.com";
string clientSecret = "redacted";
string username = "username@redacted.onmicrosoft.com";
string password = "redacted";

AuthenticationResult authenticationResult = null;
AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

var userCred = new UserPasswordCredential(username, password);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

string errorMessage = null;
try
{
Console.WriteLine("Trying to acquire token");
authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientId, userCred).Result;
}
catch (AdalException ex)
{
errorMessage = ex.Message;
if (ex.InnerException != null)
{
errorMessage += "nInnerException : " + ex.InnerException.Message;
}
}
catch (ArgumentException ex)
{
errorMessage = ex.Message;
}
if (!string.IsNullOrEmpty(errorMessage))
{
Console.WriteLine("Failed: {0}" + errorMessage);
return;
}
Console.WriteLine("nMaking the protocol calln");
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new OAuthCredentials(authenticationResult.AccessToken);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.Url = new Uri(resource + "/EWS/Exchange.asmx");
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("redacted@gmail.com");
email.Subject = "HelloWorld from EWS";
email.Body = new MessageBody("Test from EWS");
email.Send();
}


This code works as intended, however, I also need to ensure that it is secure/according to best practice.



When using the code, I registered the application as "Native", however, I have later found that Micrsofts manual says you should not use client_secret with Native applications, and the client secret is not actually used by the code either in its current form.



Considering the use case (non-interactive service authenticate as one specific user), is this the correct approach?



What should I consider when registering the service in AAD?










share|improve this question





























    0















    I am building a daemon/non-interactive service to use EWS in O365 as a specific user. In order to communicate with EWS over OAUTH2.0 I am trying to properly register the application and authenticate against AAD. Preferably I would like to use certificate based authentication, but I did not get that far.



    The code is below (its working):



        static void Main(string args)
    {
    string tenant = "redacted.onmicrosoft.com";
    string authority = "https://login.microsoftonline.com/" + tenant;
    string clientId = "44964df2-3333-2222-1111-redcated";
    string resource = "https://outlook.office365.com";
    string clientSecret = "redacted";
    string username = "username@redacted.onmicrosoft.com";
    string password = "redacted";

    AuthenticationResult authenticationResult = null;
    AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

    var userCred = new UserPasswordCredential(username, password);
    ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

    string errorMessage = null;
    try
    {
    Console.WriteLine("Trying to acquire token");
    authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientId, userCred).Result;
    }
    catch (AdalException ex)
    {
    errorMessage = ex.Message;
    if (ex.InnerException != null)
    {
    errorMessage += "nInnerException : " + ex.InnerException.Message;
    }
    }
    catch (ArgumentException ex)
    {
    errorMessage = ex.Message;
    }
    if (!string.IsNullOrEmpty(errorMessage))
    {
    Console.WriteLine("Failed: {0}" + errorMessage);
    return;
    }
    Console.WriteLine("nMaking the protocol calln");
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
    service.Credentials = new OAuthCredentials(authenticationResult.AccessToken);
    service.TraceEnabled = true;
    service.TraceFlags = TraceFlags.All;
    service.Url = new Uri(resource + "/EWS/Exchange.asmx");
    EmailMessage email = new EmailMessage(service);
    email.ToRecipients.Add("redacted@gmail.com");
    email.Subject = "HelloWorld from EWS";
    email.Body = new MessageBody("Test from EWS");
    email.Send();
    }


    This code works as intended, however, I also need to ensure that it is secure/according to best practice.



    When using the code, I registered the application as "Native", however, I have later found that Micrsofts manual says you should not use client_secret with Native applications, and the client secret is not actually used by the code either in its current form.



    Considering the use case (non-interactive service authenticate as one specific user), is this the correct approach?



    What should I consider when registering the service in AAD?










    share|improve this question



























      0












      0








      0








      I am building a daemon/non-interactive service to use EWS in O365 as a specific user. In order to communicate with EWS over OAUTH2.0 I am trying to properly register the application and authenticate against AAD. Preferably I would like to use certificate based authentication, but I did not get that far.



      The code is below (its working):



          static void Main(string args)
      {
      string tenant = "redacted.onmicrosoft.com";
      string authority = "https://login.microsoftonline.com/" + tenant;
      string clientId = "44964df2-3333-2222-1111-redcated";
      string resource = "https://outlook.office365.com";
      string clientSecret = "redacted";
      string username = "username@redacted.onmicrosoft.com";
      string password = "redacted";

      AuthenticationResult authenticationResult = null;
      AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

      var userCred = new UserPasswordCredential(username, password);
      ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

      string errorMessage = null;
      try
      {
      Console.WriteLine("Trying to acquire token");
      authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientId, userCred).Result;
      }
      catch (AdalException ex)
      {
      errorMessage = ex.Message;
      if (ex.InnerException != null)
      {
      errorMessage += "nInnerException : " + ex.InnerException.Message;
      }
      }
      catch (ArgumentException ex)
      {
      errorMessage = ex.Message;
      }
      if (!string.IsNullOrEmpty(errorMessage))
      {
      Console.WriteLine("Failed: {0}" + errorMessage);
      return;
      }
      Console.WriteLine("nMaking the protocol calln");
      ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
      service.Credentials = new OAuthCredentials(authenticationResult.AccessToken);
      service.TraceEnabled = true;
      service.TraceFlags = TraceFlags.All;
      service.Url = new Uri(resource + "/EWS/Exchange.asmx");
      EmailMessage email = new EmailMessage(service);
      email.ToRecipients.Add("redacted@gmail.com");
      email.Subject = "HelloWorld from EWS";
      email.Body = new MessageBody("Test from EWS");
      email.Send();
      }


      This code works as intended, however, I also need to ensure that it is secure/according to best practice.



      When using the code, I registered the application as "Native", however, I have later found that Micrsofts manual says you should not use client_secret with Native applications, and the client secret is not actually used by the code either in its current form.



      Considering the use case (non-interactive service authenticate as one specific user), is this the correct approach?



      What should I consider when registering the service in AAD?










      share|improve this question
















      I am building a daemon/non-interactive service to use EWS in O365 as a specific user. In order to communicate with EWS over OAUTH2.0 I am trying to properly register the application and authenticate against AAD. Preferably I would like to use certificate based authentication, but I did not get that far.



      The code is below (its working):



          static void Main(string args)
      {
      string tenant = "redacted.onmicrosoft.com";
      string authority = "https://login.microsoftonline.com/" + tenant;
      string clientId = "44964df2-3333-2222-1111-redcated";
      string resource = "https://outlook.office365.com";
      string clientSecret = "redacted";
      string username = "username@redacted.onmicrosoft.com";
      string password = "redacted";

      AuthenticationResult authenticationResult = null;
      AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

      var userCred = new UserPasswordCredential(username, password);
      ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

      string errorMessage = null;
      try
      {
      Console.WriteLine("Trying to acquire token");
      authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientId, userCred).Result;
      }
      catch (AdalException ex)
      {
      errorMessage = ex.Message;
      if (ex.InnerException != null)
      {
      errorMessage += "nInnerException : " + ex.InnerException.Message;
      }
      }
      catch (ArgumentException ex)
      {
      errorMessage = ex.Message;
      }
      if (!string.IsNullOrEmpty(errorMessage))
      {
      Console.WriteLine("Failed: {0}" + errorMessage);
      return;
      }
      Console.WriteLine("nMaking the protocol calln");
      ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
      service.Credentials = new OAuthCredentials(authenticationResult.AccessToken);
      service.TraceEnabled = true;
      service.TraceFlags = TraceFlags.All;
      service.Url = new Uri(resource + "/EWS/Exchange.asmx");
      EmailMessage email = new EmailMessage(service);
      email.ToRecipients.Add("redacted@gmail.com");
      email.Subject = "HelloWorld from EWS";
      email.Body = new MessageBody("Test from EWS");
      email.Send();
      }


      This code works as intended, however, I also need to ensure that it is secure/according to best practice.



      When using the code, I registered the application as "Native", however, I have later found that Micrsofts manual says you should not use client_secret with Native applications, and the client secret is not actually used by the code either in its current form.



      Considering the use case (non-interactive service authenticate as one specific user), is this the correct approach?



      What should I consider when registering the service in AAD?







      oauth-2.0 azure-active-directory






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 12:01







      agnsaft

















      asked Nov 13 '18 at 10:57









      agnsaftagnsaft

      33251738




      33251738
























          1 Answer
          1






          active

          oldest

          votes


















          -1















          I have later found that Micrsofts manual says you should not use
          client_secret with Native applications




          Client_secret cannot be used in a native app (public client), because client_secrets cannot be reliably stored on devices. It is required for web apps and web APIs (all confidential clients), which have the ability to store the client_secret securely on the server side.




          Considering the use case (non-interactive service authenticate as one
          specific user), is this the correct approach?




          Yes, the OAuth 2.0 Client Credentials Grant Flow permits a web service (confidential client) to use its own credentials instead of impersonating a user, to authenticate when calling another web service. While Oauth 2.0 auth code grant flow and OpenId Connect is impersonating a user that needs the user sign in.




          What should I consider when registering the service in AAD?




          You could read this doc, it will introduce the main structure about the AAD service.






          share|improve this answer


























          • This answer does not help at all. Client Credentials Grant Flow is out of the question due to its extensive need for access rights (i.e. give access to all users mailbokses rather than 1 single user). Auth Code grant flow is out of the question for a non-interactive service as it does not allow signin without a browser popup (with ADAL). Regarding the doc: I have read through it several times. Microsofts manual does a poor job in mapping OAUTH2.0 to ADAL and AAD app registration. When are the different grant flows used in ADAL? What should be the correct app type in AAD for these?

            – agnsaft
            Nov 14 '18 at 9:11











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53279493%2fservice-authenticating-against-azure-ad-and-ews%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          -1















          I have later found that Micrsofts manual says you should not use
          client_secret with Native applications




          Client_secret cannot be used in a native app (public client), because client_secrets cannot be reliably stored on devices. It is required for web apps and web APIs (all confidential clients), which have the ability to store the client_secret securely on the server side.




          Considering the use case (non-interactive service authenticate as one
          specific user), is this the correct approach?




          Yes, the OAuth 2.0 Client Credentials Grant Flow permits a web service (confidential client) to use its own credentials instead of impersonating a user, to authenticate when calling another web service. While Oauth 2.0 auth code grant flow and OpenId Connect is impersonating a user that needs the user sign in.




          What should I consider when registering the service in AAD?




          You could read this doc, it will introduce the main structure about the AAD service.






          share|improve this answer


























          • This answer does not help at all. Client Credentials Grant Flow is out of the question due to its extensive need for access rights (i.e. give access to all users mailbokses rather than 1 single user). Auth Code grant flow is out of the question for a non-interactive service as it does not allow signin without a browser popup (with ADAL). Regarding the doc: I have read through it several times. Microsofts manual does a poor job in mapping OAUTH2.0 to ADAL and AAD app registration. When are the different grant flows used in ADAL? What should be the correct app type in AAD for these?

            – agnsaft
            Nov 14 '18 at 9:11
















          -1















          I have later found that Micrsofts manual says you should not use
          client_secret with Native applications




          Client_secret cannot be used in a native app (public client), because client_secrets cannot be reliably stored on devices. It is required for web apps and web APIs (all confidential clients), which have the ability to store the client_secret securely on the server side.




          Considering the use case (non-interactive service authenticate as one
          specific user), is this the correct approach?




          Yes, the OAuth 2.0 Client Credentials Grant Flow permits a web service (confidential client) to use its own credentials instead of impersonating a user, to authenticate when calling another web service. While Oauth 2.0 auth code grant flow and OpenId Connect is impersonating a user that needs the user sign in.




          What should I consider when registering the service in AAD?




          You could read this doc, it will introduce the main structure about the AAD service.






          share|improve this answer


























          • This answer does not help at all. Client Credentials Grant Flow is out of the question due to its extensive need for access rights (i.e. give access to all users mailbokses rather than 1 single user). Auth Code grant flow is out of the question for a non-interactive service as it does not allow signin without a browser popup (with ADAL). Regarding the doc: I have read through it several times. Microsofts manual does a poor job in mapping OAUTH2.0 to ADAL and AAD app registration. When are the different grant flows used in ADAL? What should be the correct app type in AAD for these?

            – agnsaft
            Nov 14 '18 at 9:11














          -1












          -1








          -1








          I have later found that Micrsofts manual says you should not use
          client_secret with Native applications




          Client_secret cannot be used in a native app (public client), because client_secrets cannot be reliably stored on devices. It is required for web apps and web APIs (all confidential clients), which have the ability to store the client_secret securely on the server side.




          Considering the use case (non-interactive service authenticate as one
          specific user), is this the correct approach?




          Yes, the OAuth 2.0 Client Credentials Grant Flow permits a web service (confidential client) to use its own credentials instead of impersonating a user, to authenticate when calling another web service. While Oauth 2.0 auth code grant flow and OpenId Connect is impersonating a user that needs the user sign in.




          What should I consider when registering the service in AAD?




          You could read this doc, it will introduce the main structure about the AAD service.






          share|improve this answer
















          I have later found that Micrsofts manual says you should not use
          client_secret with Native applications




          Client_secret cannot be used in a native app (public client), because client_secrets cannot be reliably stored on devices. It is required for web apps and web APIs (all confidential clients), which have the ability to store the client_secret securely on the server side.




          Considering the use case (non-interactive service authenticate as one
          specific user), is this the correct approach?




          Yes, the OAuth 2.0 Client Credentials Grant Flow permits a web service (confidential client) to use its own credentials instead of impersonating a user, to authenticate when calling another web service. While Oauth 2.0 auth code grant flow and OpenId Connect is impersonating a user that needs the user sign in.




          What should I consider when registering the service in AAD?




          You could read this doc, it will introduce the main structure about the AAD service.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 1:20

























          answered Nov 14 '18 at 1:14









          SunnySunSunnySun

          1,048118




          1,048118













          • This answer does not help at all. Client Credentials Grant Flow is out of the question due to its extensive need for access rights (i.e. give access to all users mailbokses rather than 1 single user). Auth Code grant flow is out of the question for a non-interactive service as it does not allow signin without a browser popup (with ADAL). Regarding the doc: I have read through it several times. Microsofts manual does a poor job in mapping OAUTH2.0 to ADAL and AAD app registration. When are the different grant flows used in ADAL? What should be the correct app type in AAD for these?

            – agnsaft
            Nov 14 '18 at 9:11



















          • This answer does not help at all. Client Credentials Grant Flow is out of the question due to its extensive need for access rights (i.e. give access to all users mailbokses rather than 1 single user). Auth Code grant flow is out of the question for a non-interactive service as it does not allow signin without a browser popup (with ADAL). Regarding the doc: I have read through it several times. Microsofts manual does a poor job in mapping OAUTH2.0 to ADAL and AAD app registration. When are the different grant flows used in ADAL? What should be the correct app type in AAD for these?

            – agnsaft
            Nov 14 '18 at 9:11

















          This answer does not help at all. Client Credentials Grant Flow is out of the question due to its extensive need for access rights (i.e. give access to all users mailbokses rather than 1 single user). Auth Code grant flow is out of the question for a non-interactive service as it does not allow signin without a browser popup (with ADAL). Regarding the doc: I have read through it several times. Microsofts manual does a poor job in mapping OAUTH2.0 to ADAL and AAD app registration. When are the different grant flows used in ADAL? What should be the correct app type in AAD for these?

          – agnsaft
          Nov 14 '18 at 9:11





          This answer does not help at all. Client Credentials Grant Flow is out of the question due to its extensive need for access rights (i.e. give access to all users mailbokses rather than 1 single user). Auth Code grant flow is out of the question for a non-interactive service as it does not allow signin without a browser popup (with ADAL). Regarding the doc: I have read through it several times. Microsofts manual does a poor job in mapping OAUTH2.0 to ADAL and AAD app registration. When are the different grant flows used in ADAL? What should be the correct app type in AAD for these?

          – agnsaft
          Nov 14 '18 at 9:11


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53279493%2fservice-authenticating-against-azure-ad-and-ews%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Full-time equivalent

          Bicuculline

          さくらももこ