Showing posts with label App Only Authentication. Show all posts
Showing posts with label App Only Authentication. Show all posts

May 20, 2021

How to send email without username and password using SMTP in C# in Office 365

Introduction:

We implemented a Console Application (C#) for a Real Estate Agency based out of Bellevue, Washington, United States. It was a part of the requirement to send an email from the Console Application using SMTP. Generally, we need the password of from email account when we send mail using SMTP, but in our case, we have to use an email account that has Okta MFA enabled.So, if we use the password for authentication, it won't work. As an alternate, we implemented the solution to send an email from C# Console Application (via SMTP) using App Only Authentication (with Azure App Registration).

Implementation:

First, we need to setup Azure App:

Setup Azure App:

Step 1: Go to https://portal.azure.com/.

Step 2: Now click on Azure Active Directory.  


Step 3: Now Click on "App Registration" from the left panel.


Step 4: Now Click on "New registration".


Step 5: Type the name of the app (a meaningful name) and click on the "Register" button.



Step 6: Now click on "App Permission" in left panel and add below API permissions:

  1. API Permission  > Microsoft Graph > Delegated Permission > User.Read
  2. API Permission > Add a permission > APIs in my organization uses > Office 365 Exchange Online > Application Permission > Other permission > full_access_as_app


Step 7: To use this permission of app, we need to get admin consent by Office 365 Global Admin user.


Step 8: Now go to "Certificates and secrets", and create a new client secret. Once this secret key created, note this secret key.


Step 9: Now click on "Overview" in the left panel to find Application (client) ID and Directory (tenant) ID.



C# Code

Step 1: Now go to your visual studio solution and add nuget package for EASendMail.


Step 2: Add below namespace in code.

 using System;  
 using EASendMail;  


Step 3: Now, use the below code to send mail:

 try  
 {  
     string client_id = "*****-****-****-****-*******";  
     string client_secret = "**************";     
     string tenant_id = "********-****-****-****-*******";   
     string requestData = string.Format("client_id={0}&client_secret={1}&scope=https://outlook.office365.com/.default&grant_type=client_credentials",  
     client_id, client_secret);  
     string tokenUri = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant_id);  
     string responseText = _postString(tokenUri, requestData);  
     OAuthResponseParser parser = new OAuthResponseParser();  
     parser.Load(responseText);  
     string officeUser = fromEmailAddress;  
     var server = new SmtpServer("outlook.office365.com");  
     server.Protocol = ServerProtocol.ExchangeEWS;  
     server.User = officeUser;  
     server.Password = parser.AccessToken;  
     server.AuthType = SmtpAuthType.XOAUTH2;  
     server.ConnectType = SmtpConnectType.ConnectSSLAuto;  
     var mail = new SmtpMail("TryIt");  
     mail.From = officeUser;  
     mail.To = toEmailAddress;  
     mail.Subject = "Office 365 background service oauth test";  
     mail.HtmlBody = "<h3>Hello</h3><p>Do not reply to this mail.</p>";  
     var smtp = new SmtpClient();  
     smtp.SendMail(server, mail);   
     Console.WriteLine("Message delivered!");  
}  
catch (Exception ex)  
{  
     Console.WriteLine(ex.ToString());  
}  


Step 4: In above code, you can see we have not used the password of the user which is selected as mail from.

Conclusion:

This is how we can send email from C# Console Application without using the password of from email address. Hope this helps!

If you have any questions you can reach out our SharePoint Consulting team here.

January 28, 2021

How to register an App only Principal in SharePoint Online?

Overview:

We implemented the Delivery Schedule application in .Net Core for a Seattle, Washington-based construction firm. The information on Delivery Sites was available in SharePoint Online, we had to query this information using REST API from SharePoint Online and display the same in the .Net Core application.

Now, to call REST API from the .Net Core application, we need to use Client ID & Client Secret (app-only authentication) as per best practices. To generate Client ID and Client Secret, we need to register the SharePoint App. In this article, we will check the registration steps for the SharePoint App. So, now let’s get started!
  1. Access following URL to open App Registration Page.
    https://<<Site Collection URL>>/_layouts/15/appregnew.aspx 
  2. This will open following screen. 
  3. Click on “Generate” for Client ID and Client Secret. 
  4. Enter the Title, App Domain and Redirect URL.
    1. Title = BRiteApp (a meaningful name)
    2. App Domain = www.localhost.com
    3. Redirect URL = https://localhost.com 
  5. Click on Create.
  6. This will give you a summary of the App you created. Copy this information for future reference.
  7. Now, access the following URL.
    https://<<Site Collection URL>>/_layouts/15/appinv.aspx 
  8. This will open the following screen.
  9. Enter the same Client ID in the App ID field that we registered in Step 3 and click on Lookup. This will auto-populate other information.
  10. Now, in “Permission Request XML" we need to provide the XML with the desired permission level information. Below is the example XML that grants Site Collection level Full Control permission to the app. For more details on the permission request options, please visit this article from Microsoft.
     <AppPermissionRequests AllowAppOnlyPolicy="true">  
     <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />  
     </AppPermissionRequests>  
    

  11. Click on Create.
  12. Click on the “Trust it” button.

Conclusion:

This is how we register our App in SharePoint Online. The registered app (Client ID & Client Secret) can be used to call the SharePoint REST APIs from the other applications.

If you have any questions you can reach out our SharePoint Consulting team here.

November 12, 2020

How to perform Azure App Only Authentication with SharePoint in .Net Core (Azure Function)

Introduction:

In the .NET Framework, there were native classes like  "SharePointCredentials" and "AuthenticatinoManager" which were used for SharePoint Authentication, but now they are removed.

The major difference compared to the .NET Framework CSOM is that the authentication is completely independent of the CSOM library now.

Resolution:

.NET standard CSOM now uses the OAuth for authentication. So we need to get an access token and pass it along with the call to SharePoint Online.

So in this blog, we will learn how to perform Azure App-Only Authentication with SharePoint in new .NET Standard CSOM to get data from SharePoint Online.

When we are using App-Only Authentication, we will have two options:
1. Azure Active Directory App Registration with the client certificate.
2. Create SharePoint App using AppRegNew.aspx and AppInv.aspx.

Here we will discuss the Azure AD App Registration approach.

Step 1:

  • First, we need to register a new app in the Azure Active Directory.
  • Go to http://portal.azure.com/ and select "Azure Active Directory". Now from the "App registrations" option in the left panel, register a new app.


Step 2:

Now we will grant the required permission to the app we created in Step 1. Open the newly created app and click on "API permissions" and click on "Add a permission".

Now select "SharePoint permission" as per your requirement and grant the admin consent. Here we needed "Full Control" permission for SharePoint so we have added "Sites.FullControl.All" and "Sites.Manage.All" permissions.


Step 3:

    1. CertificateName.cert
    2. CertificateName.pfx
  • Consideration: Keep note of the password which you have used to generate a certificate.

Step 4:

  • Now we will configure this certificate with our Azure AD App. 
  • Go to your Azure AD App. Now click on "Certificates and client" from the left panel and click on the "Upload certificate" button.
  • On clicking the "Upload certificate", it will open a panel at the top and allows you to upload the file. Here you need to upload the ".cert" file.

Step 5:

  • Make sure you have selected all required permissions in API Permissions and admin consent has been granted for all required permissions.

Step 6:

  • Now we will create an Azure Function solution using Visual Studio 2019.


Step 7:


Step 8:

  • Now in the Azure Function solution, we need to read the ".pfx" file which is uploaded in our solution. To read the file from the Azure Function solution we need execution context.
  • We can get the execution context using the below parameter in the Azure Function:
          
 ExecutionContext executionContext  

  • Below is the code snippet for how to use execution context:
 [FunctionName("Function1")]  
 public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext executionContext)  

  • Now using this execution context, we can get the ".pfx" file as below:
 var Sfilepath = $"{ System.IO.Directory.GetParent(executionContext.FunctionDirectory).FullName}\\Certificate\\CertificateFilename.pfx";  

  • Here we have uploaded the file in the Certificate folder. So the Sfilepath variable we are reading a file from the Certificate folder.

Step 9:

  • Now we will get ClientContext using this Certificate File and Application ID.
  • To get the context, first, we need an access token.
  • To get the access token we need Application ID, Certificate File Path, Certificate File Password, Tenant ID, and Permission Scope.
  • Permission scope will be as below:
  public static string[] permissionscopes = { "https://tenantname.sharepoint.com/.default" };  

  • We will use the below method to get the access token:
 internal static async Task<string> GetApplicationAuthenticatedClient(string clientId, string Sfilepath, string certificatePassword, string[] scopes, string tenantId)  
     {  
       X509Certificate2 certificate = new X509Certificate2(certThumprint, certificatePassword", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);  
       IConfidentialClientApplication clientApp;  
       clientApp = ConfidentialClientApplicationBuilder  
       .Create(clientId)  
       .WithCertificate(certificate)  
       .WithTenantId(tenantId)  
       .Build();  
       AuthenticationResult authResult = await clientApp.AcquireTokenForClient(scopes).ExecuteAsync();  
       string accessToken = authResult.AccessToken;  
       return accessToken;  
     }  

  • We can call the above method as below:
 var accessToken = await GetApplicationAuthenticatedClient(clientId, Sfilepath, certificatePassword, permissionscopes, tenantId);  

  • Now the "accessToken" variable will contain the access token.

Step 10:

  • Now using the access token which we get in Step 8, we will generate client context.
  • We can use the below method, which will return the client context. We will need the Site URL for which we want the client context and the access token.
 public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)  
     {  
       ClientContext clientContext = new ClientContext(targetUrl);  
       clientContext.ExecutingWebRequest +=  
       delegate (object oSender, WebRequestEventArgs webRequestEventArgs)  
       {  
         webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =  
   "Bearer " + accessToken;  
       };  
       return clientContext;  
     }  

  • We can call the above method as below:
 var clientCtx = GetClientContextWithAccessToken(siteUrl, accessToken);  

Step 11:

  • Now we have the client context of the Site URL which you have used in step 9.
  • So we can now use the client context for any operations we want to perform programmatically with CSOM.
 Web web = clientCtx.Web;  
 clientCtx.Load(web);  
 clientCtx.ExecuteQuery();  

Conclusion:

This is how we can authenticate to SharePoint from .Net Core with the use of Azure App-Only Authentication. 

If you have any questions you can reach out our SharePoint Consulting team here.