gpt4 book ai didi

c# - 如何在没有控制台/ native 应用程序交互式登录屏幕的情况下为 Graph API 生成 Azure Active Directory (AAD) 身份验证 token ?

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:01 24 4
gpt4 key购买 nike

如何在没有控制台/ native 应用程序交互式登录屏幕的情况下为 Graph API 生成 Azure Active Directory (AAD) 身份验证 token ?

详细信息:我正在使用 Graph API 阅读带有“委托(delegate)”权限​​的 Azure Active Directory (AAD) 的电子邮件。

“应用程序”权限允许用户阅读其他邮箱,出于安全考虑,此方法未经管理员同意,因此我使用“委派”权限。

我的控制台/ native 应用程序已注册到 AAD。

由于 AAD 使用以下方法为特定帐户生成 OAuth 身份验证 token :1.客户编号2.租户ID3. Client Secret(应用程序的 key /密码)4. 特定帐户的登录凭据。

我可以使用交互式登录屏幕生成 token 。

但是,我想要一种机制,在该机制中,我可以使用 C# 或 .NET 为图形 API(资源)生成 AAD token ,而无需在代码中使用交互式登录屏幕

最佳答案

您似乎试图在不提示登录页面的情况下获取您的 token 。

是的,您可以使用 client_credentials 来做到这一点在 C#.Net 内授予身份验证流程

请看下面的代码片段:

访问 token 类:

 public  class AccessTokenClass
{
public string access_token { get; set; }
public string token_type { get; set; }
public long expires_in { get; set; }
}

token 请求方法:

private async Task<string> GetYourTokenWithClientCredentialsFlow()
{
string tokenUrl = $"https://login.microsoftonline.com/YourTenant/oauth2/token";
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "client_credentials",
["client_id"] = "5f14dea0-5cd---Your_Client_Id----8950-4f646829f870",
["client_secret"] = "031Fnwih---Your_Client_Secret----Fx+Ase3V65lpWQ=",
["resource"] = "https://graph.microsoft.com" // https://management.azure.com/ Or Any Resource You Want
});

dynamic json;
dynamic token;
HttpClient client = new HttpClient();

var tokenResponse = await client.SendAsync(tokenRequest);

json = await tokenResponse.Content.ReadAsStringAsync();
token = JsonConvert.DeserializeObject<AccessTokenClass>(json);
Console.WriteLine("Your Access Token {0}",token.access_token);
return token;
}

生成的 token 响应:

一旦您设置了所有必需的凭据,您将获得 token 作为响应。请参见下面的屏幕截图:

enter image description here

Note: This authentication flow would generate token for you without interactive login screen. If you still have any query feel free to share in comment. Thanks and happy coding!

更新:

分配阅读邮件的专用权限。请按照以下步骤操作:

  1. Azure 事件目录
  2. 应用注册
  3. 选择您的应用
  4. API 权限
  5. 添加权限
  6. 微软图谱
  7. 委派的权限
  8. 邮件
  9. Mail.Read(读取用户邮件)
  10. 添加权限
  11. 授予管理员同意

查看屏幕截图:

enter image description here

关于c# - 如何在没有控制台/ native 应用程序交互式登录屏幕的情况下为 Graph API 生成 Azure Active Directory (AAD) 身份验证 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56353142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com