我正在尝试从 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/