-1

Hello Folks I am new to using API into my project. I am using Asp.Net with C# which does not have MVC architecture. My client needed to integrate office 365 API into the project so that any user who want to access our service can login through their office 365 credentials. while I searched on internet about the sources it said I needed ASP.net with MVC to use office 365 . Please suggest what could be done.

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

0

You could use Active Directory Authentication Library .NET to easily authenticate users to cloud or on-premises Active Directory (AD), and then obtain access tokens for securing API calls . In web form , code below is for your reference :

        protected  void Page_Load(object sender, EventArgs e)
        {
        string authCode = Request.Params["code"];
        if (!string.IsNullOrEmpty(authCode))
        {
             Authorize(authCode);
        }

        string token = (string)Session["access_token"];
        if (string.IsNullOrEmpty(token))
        {
            return;
        }
        try
        {
            // get user name
            getUserName(token);
        }
        catch (AdalException ex)
        {

        }
    }

    public void getUserName(string token)
    {
        using (var client = new HttpClient())
        {
            //Enable signon and read users' profile
            using (var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/beta/me"))
            {
                request.Headers.Add("Authorization", "Bearer " + token);
                request.Headers.Add("Accept", "application/json;odata.metadata=minimal");
                using (var response = client.SendAsync(request).Result)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                        Response.Write(json["displayName"].ToString());
                    }
                }
            }
        }
    }

    public void Authorize(string authCode) {
        AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common");

        // The same url we specified in the auth code request
        string redirectUri = "http://localhost:55065/Default.aspx";

        // Use client ID and secret to establish app identity
        ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ClientID"], ConfigurationManager.AppSettings["ClientSecret"]);

        try
        {
            // Get the token
            var authResult =  authContext.AcquireTokenByAuthorizationCode(
                authCode, new Uri(redirectUri), credential, "https://graph.microsoft.com/");

            // Save the token in the session
            Session["access_token"] = authResult.AccessToken;


            Response.Redirect(redirectUri.ToString());
        }
        catch (AdalException ex)
        {
            //return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
        }
    }
    public void signin()
    {
        var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");


        // The url in our app that Azure should redirect to after successful signin 
        string redirectUri = "http://localhost:55065/Default.aspx";


        // Generate the parameterized URL for Azure signin 
        Uri authUri = authContext.GetAuthorizationRequestURL("https://graph.microsoft.com/", ConfigurationManager.AppSettings["ClientID"],
            new Uri(redirectUri), UserIdentifier.AnyUser, null);

        // Redirect the browser to the Azure signin page 
        Response.Redirect(authUri.ToString());
    }

You could also refer to below link to get some examples with O365 API in GitHub : https://github.com/dream-365/OfficeDev-Samples/tree/master/samples/Office365DevQuickStart

But I would suggest you could try to use ASP.NET MVC , it is designed with separation of concerns and testability in mind , and you will find a lot of MVC samples with O365 in here: Office 365 API code samples and videos

Nan Yu
  • 26,101
  • 9
  • 68
  • 148