将 Office 365 与 C# WebForms 应用程序集成

integrate office 365 with C# WebForms Applications

是否支持 WebForms C# 应用程序(非 MVC)?还是解决方法?如果我想将现有成熟的 C# webforms 应用程序与 office 365 身份验证集成并且不想重写整个应用程序。

要从 Azure AD 实现 OAuth 身份验证,我们可以使用以下代码编写代码将用户重定向到登录页面(从登录按钮单击):

   {
        var authority = "https://login.microsoftonline.com";
        var tenant = "common";
        var authorizeSuffix = "oauth2";

        var EndPointUrl = String.Format("{0}/{1}/{2}/authorize?", authority, tenant, authorizeSuffix);

        var clientId = "";
        var redirectURL = "http://localhost:56384/auth.aspx";         
        var parameters = new Dictionary<string, string>
            {
                { "response_type", "code" },
                { "client_id", clientId },
                { "redirect_uri", redirectURL },
                { "prompt", "login"}
            };

        var list = new List<string>();

        foreach (var parameter in parameters)
        {
            if (!string.IsNullOrEmpty(parameter.Value))
                list.Add(string.Format("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value)));
        }
        var strParameters = string.Join("&", list);
        var requestURL=String.Concat(EndPointUrl,strParameters);

        Response.Redirect(requestURL);

    }

用户登录Azure AD后,会重定向到我们在Azure上配置的redirectURL。我们可以将其配置到特定页面以获取 AUTH Code 并请求令牌。这是一个例子:

Auth.aspx:

   protected void Page_Load(object sender, EventArgs e)
    {
        var authority = "https://login.microsoftonline.com";
        var tenant = "common";
        var authorizeSuffix = "oauth2";
        var EndPointUrl = String.Format("{0}/{1}/{2}", authority, tenant, authorizeSuffix);

        var code = Request.QueryString["code"].ToString();

        var clientId = "";
        var resource = "https://graph.microsoft.com";
        var secrect = "";
        var redirectURL = "http://localhost:56384/auth.aspx";

        //Request access token
        var parameters = new Dictionary<string, string>
            {
                { "resource", resource},
                { "client_id", clientId },
                { "code",  code},
                { "grant_type", "authorization_code" },
                { "redirect_uri", redirectURL},
                { "client_secret",secrect}
            };


        var list = new List<string>();

        foreach (var parameter in parameters)
        {
            if (!string.IsNullOrEmpty(parameter.Value))
                list.Add(string.Format("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value)));
        }
        var strParameters = string.Join("&", list);


        var content = new StringContent(strParameters, Encoding.GetEncoding("utf-8"), "application/x-www-form-urlencoded");

        var client = new HttpClient();

        var url = string.Format("{0}/token", EndPointUrl);

        var response = client.PostAsync(url, content).Result;

        var text = response.Content.ReadAsStringAsync().Result;

        var result = JsonConvert.DeserializeObject(text) as JObject;

        var AccessToken = result.GetValue("access_token").Value<string>();
        var RefreshToken = result.GetValue("refresh_token").Value<string>();

        Session["accessToken"] = AccessToken;
        Session["refreshToken"] = AccessToken;


        //add code read the user info from access token for login in


    }

Authorization Code Grant Flow的详细内容可以参考here

更新

从访问令牌中提取用户名:

string accessToken = "";

byte[] data = Convert.FromBase64String(accessToken.Split('.')[1]);
string decodedString = Encoding.UTF8.GetString(data);

JToken token = JObject.Parse(decodedString);            
Console.WriteLine(token["name"].Value<string>());