azure - 无需用户登录即可从 Azure 应用程序访问 token

标签 azure azure-active-directory

我正在尝试从 Azure 为我的应用程序获取 AccessToken。我一直在尝试从 here第 4 节。不幸的是,当我编写下面的代码来获取访问 token 时。它说错误的请求。这是我正在尝试的代码

string gUrl = "https://login.microsoftonline.com/0000000000-49d7-9734-d930e2db05de/oauth2/v2.0/token";

string ss = "{"+
                              "\"client_id\": \"some Id of Client\","+
                              "\"scope\": \"https%3A%2F%2Fgraph.microsoft.com%2F.default\"," +
                              "\"client_secret\": \"\"," +
                              "\"grant_type\": \"client_credentials\""+
                             
                          "}";

var payload = new StringContent(JsonConvert.DeserializeObject(ss).ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");

public static string GraphToken(string urlService,StringContent postValue)
        {
            try
            {
                string request = string.Empty;
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    //httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", token))));
                    using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(new HttpMethod("POST"), urlService) { Content = postValue })
                    {
                        var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;
                        if (httpResponseMessage.IsSuccessStatusCode)
                        {
                            request = httpResponseMessage.Content.ReadAsStringAsync().Result;
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.Write("success");
                            Console.ResetColor();
                        }
                    }
                }
                return request;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        } 

有人可以帮我解决这个问题吗?

最佳答案

如果你想在没有用户登录的情况下获取访问 token ,可以使用下面的代码,我认为这比在代码中调用http请求更容易。

using Microsoft.Identity.Client;
using System;
using System.Threading.Tasks;

namespace ConsoleApp27
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                .Create("<client id>")
                .WithTenantId("<tenant id>")
                .WithClientSecret("<client secret>")
                .Build();

            var scopes = new string[] { "https://graph.microsoft.com/.default" };

            var authResult = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();

            Console.WriteLine(authResult.AccessToken);
        }
    }
}

你只需要安装这个nuget运行上面的代码。

关于azure - 无需用户登录即可从 Azure 应用程序访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63389402/

相关文章:

azure - 除了使用登录卡之外,还有其他方法在机器人中登录用户吗?

asp.net - 如何使用 Azure Active Directory 作为我的 Webform 和 MVC 应用程序的身份提供程序?

azure - 有一些如何备份 Azure AD B2C 的方法吗?

默认情况下,使用 Azure Active Directory 登录页面托管在 IIS 中的 ASP.NET Web 应用程序

azure - 如何获取事件版本所基于的分支的名称?

azure - 如何将具有相同 ID 的值复制到列中? Azure 数据工厂

c# - 如何在asp.net中传递查询字符串参数?

python - 在 AzureML 中未获得预期输出

azure - Blazor + Azure AD 身份验证 : Single Tenant login giving "Sorry, there' s nothing at this address"

azure - Asp 核心 2.2 Azure 事件目录 : Authorization failed