首页 > 解决方案 > Microsoft Graph - 资源所有者密码凭据替代

问题描述

这是上下文:

这是场景:

这是问题所在:

这是我的丑陋修复:

    public async Task<string> GetTokenUser(string email, string password) 
    {
        string token = null;
        var clientID = "<ApplicationClientID>";
        var secret = "<ApplicationSecret>";
        var tenantID = HttpUtility.UrlEncode("<TenantDomain>");
        var resource = HttpUtility.UrlEncode("https://graph.microsoft.com");
        email= HttpUtility.UrlEncode(email);
        password= HttpUtility.UrlEncode(password);

        using (HttpClient client = new HttpClient())
        {
            var tokenEndpoint = @"https://login.windows.net/" + tenantID + "/oauth2/token";
            var accept = "application/json";

            client.DefaultRequestHeaders.Add("Accept", accept);
            string postBody = @"resource=" + resource + @"
                                &client_id=" + clientID + @"
                                &client_secret=" + secret  + @"
                                &grant_type=password
                                &username=" + email + @"
                                &password=" + password + "&scope=openid";

            using (var response = await client.PostAsync(tokenEndpoint, new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded")))
            {
                if (response.IsSuccessStatusCode)
                {
                    var jsonresult = JObject.Parse(await response.Content.ReadAsStringAsync());
                    token = (string)jsonresult["access_token"];
                }
            }
        }

        return token;
    }

这是我需要的:

重要说明:只要它有效且可靠,我对如何实现这一点绝对没有偏好。

编辑1:代码中的错字

标签: c#oauth-2.0asp.net-mvc-5azure-active-directorymicrosoft-graph-api

解决方案


如果要访问 Microsoft Graph,则需要 Azure AD 身份验证。

Create onlineMeeting仅支持 Delegated 权限,这意味着您必须按照代表用户获取访问权限才能获取访问令牌。

所以如果你不想使用 ROPC 流程,你需要将 AAD 授权登录集成到你的项目中。

请按照本文档了解如何操作。


推荐阅读