AcquireTokenAsync函数不会返回任何响应

问题描述 投票:1回答:2

我正在尝试使用下面提到的代码从Web应用程序中获取AzureAD中所有office365用户的列表。但是,authContext.AcquireTokenAsync(resrouce,clientCredential)永远不会返回控件。我已尝试下面的控制台应用程序代码,它工作得很好。但是,我很想知道为什么代码不能用于Web,或者我需要做些什么修改才能使代码在Web上运行。

public static async Task<string> AcquireMyToken()
        {
            string clientId = "";
            string secrect = "";
            string resrouce = "https://graph.microsoft.com";
            string authority = "https://login.microsoftonline.com/tenanId";
            AuthenticationContext authContext = new AuthenticationContext(authority);
            ClientCredential clientCredential = new ClientCredential(clientId, secrect);
            AuthenticationResult authResult = await authContext.AcquireTokenAsync(resrouce, clientCredential);
            return authResult.AccessToken;
        } 


public static async void ListFiles(string accessToken)
        {
            var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
             (requestMessage) =>
             {
                 requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                 return Task.FromResult(0);
             }));    
            var users = await graphClient.Users.Request().GetAsync();                  
        }      
azure asp.net-web-api c#-4.0 azure-active-directory office365api
2个回答
0
投票

关于这个问题,您需要在Controller和html中指定您的代码。有一个样本如下。

public async Task<ActionResult> Test()
        {

            string clientId = "";
            string secrect = "";
            string resrouce = "https://graph.microsoft.com";
            string authority = "https://login.microsoftonline.com/tenanId";
            AuthenticationContext authContext = new AuthenticationContext(authority);
            ClientCredential clientCredential = new ClientCredential(clientId, secrect);
            AuthenticationResult authResult = await authContext.AcquireTokenAsync(resrouce, clientCredential);
            var token = authResult.AccessToken;
            var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
                requestMessage
                    .Headers
                    .Authorization = new AuthenticationHeaderValue("bearer", token);

                return Task.FromResult(0);
            }));
           // var events = await graphServiceClient.Me.Events.Request().GetAsync();
            var users = await graphServiceClient.Users.Request().GetAsync();

            IList<User> userlist = users.CurrentPage;

            return View(userlist);
        }

HTML:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Sign-In with Microsoft Sample</title>
    <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
</head>
<body style="padding:50px">
    <!--show the message your need-->
    <table class="table">
        <thead>
            <tr>
                <th scope="col">userPrincipalName</th>

                <th scope="col">Mail</th>

            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.UserPrincipalName</td>
                    <td>@item.Mail</td>

                </tr>
            }
        </tbody>
    </table>
</body>
</html>

有关详细信息,请参阅https://github.com/microsoftgraph/msgraph-training-aspnetmvcapp


0
投票

对于您的控制台应用程序上的测试,您可以替换以下代码:

static async Task AccessMicrosoftUserData()
        {

            string clientId = "Your application Application Id";
            string secrect =  "Your application secret Id";
            string resrouce = "https://graph.microsoft.com";
            string authority = "https://login.microsoftonline.com/YourTenantId";
            // For example 
            // string authority = "https://login.microsoftonline.com/b6603c7be-a866-4666-ad87-e6921e61f999";
            AuthenticationContext authContext = new AuthenticationContext(authority);

            //Checking  application authenticity
            ClientCredential clientCredential = new ClientCredential(clientId, secrect);

            AuthenticationResult authResult = await authContext.AcquireTokenAsync(resrouce, clientCredential);
            //Generating Token with your credentails
            var accessToken = authResult.AccessToken;

            var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
                requestMessage
                    .Headers
                    .Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                return Task.FromResult(0);
            }));
            //You may encounter request denial here if you don't have resource access 
              Privilege
            //To avoid this see the screen shot below.

            var users = await graphServiceClient.Users.Request().GetAsync();

        }

现在调用主方法像这样:

 static void Main(string[] args)
        {


            AccessMicrosoftUserData().Wait();

        }

Web示例

var request = new HttpRequestMessage(HttpMethod.Post, "http://server.com/token");
request.Content = new FormUrlEncodedContent(new Dictionary<string, string> {
    { "client_id", "your client_id" },
    { "client_secret", "your client_secret" },
    { "grant_type", "client_credentials" }
});

var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();

var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var token = payload.Value<string>("access_token");

注意:在上面的代码中,http://server.com/token应该是您的令牌端点,例如https://login.microsoftonline.com/YourTenantID/oauth2/v2.0/token

对于实现复杂性,您可以检查here。如果你需要更多关于划痕开发的想法,你也可以参考this

注意:如果您没有资源访问权限,可能会遇到请求拒绝权限要避免这种情况,请参阅下面的屏幕截图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.