How To Authenticate Users With Office 365 WebForm Application

Last week, I had a requirement to authenticate users. I did search Google but all the solutions support Owin and related libs, MVC etc.There is no solution for Web form application with .NET 4.0.
 
For this, you have to follow these steps -
 
Create application using Microsoft account at this URL.
 
 
  • Mention Redirect URL where you want to hit after authentication.
  • Copy AppId that will help us later.
  • In Login.aspx, create a button, and onclick of this button, write the following code.
  1. <input type="button" ID="BtnSignInMicrosoft" Class="bofficesignin" runat="server" value="Sign in with Office 365" onclick="RedirectToOffice(); return false;" /> and javascript code function RedirectToOffice() { var OfficeRedirectUrl = "  
  2. <%=ConfigurationManager.AppSettings("YourRediectURL mention on application creation")%>"; var Office365ClientId = "  
  3.     <%=ConfigurationManager.AppSettings("Office365ClientId")%>"; var OfficeUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?response_type=id_token+token&client_id="+ Office365ClientId +"&redirect_uri=" + OfficeRedirectUrl + "&scope=openid+https%3A%2F%2Foutlook.office.com%2Fmail.read&nonce=13c9217a-d565-fb9e-d66d-d5ad18fa6f0b&response_mode=form_post"; window.open(OfficeUrl,"_self"); }  
Write the following code on your redirect page.
  1. If Request.Form.Item("id_token") Is Nothing = False Then  
  2. Dim objWebClient As New System.Net.WebClient  
  3. Dim HeaderData As New WebHeaderCollection  
  4. Dim jSerializer As New JavaScriptSerializer  
  5. Dim ResponseString As String = String.Empty  
  6. Dim ResponseData As Dictionary(Of String, String)  
  7. Dim Email As String = String.Empty  
  8. Dim TokenID As String = Request.Form.Item("id_token")  
  9. Dim AccessToken As String = Request.Form.Item("access_token")  
  10. TokenID = TokenID.Substring(0, TokenID.IndexOf("."))  
  11. HeaderData("Authorization") = "Bearer " + AccessToken  
  12. ' Dim objOutlookSetting As OutLookSetting = Serializar.Deserialize(Of OutLookSetting)(BLL.SettingManager.GetValueByKey("EAAdminOutlookSetting"))  
  13. HeaderData("client-request-id") = ConfigurationManager.AppSettings("Office365ClientId")  
  14. HeaderData("return-client-request-id") = "true"  
  15. objWebClient.Headers = HeaderData  
  16. ResponseString = objWebClient.DownloadString("https://outlook.office.com/api/v2.0/Me")  
  17. ResponseData = jSerializer.Deserialize(Of Dictionary(Of String, String))(ResponseString)  
  18. Email = ResponseData("EmailAddress")  
And, the rest of the flow will remain the same in your application.