azure 我的请求仅对.Net Core API中的Graph API中的委托身份验证流有效

xdnvmnnf  于 2023-03-13  发布在  .NET
关注(0)|答案(2)|浏览(187)

我有一个.net核心API和用户。授予了读取委托权限。startup.cs中的身份验证部分:

services.AddAuthentication("Bearer")
        .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));

获取图形API客户端:

var credential = new DefaultAzureCredential();
                    var token = credential.GetToken(
                            new Azure.Core.TokenRequestContext(
                                new[] { "https://graph.microsoft.com/.default" }));
                    var accessToken = token.Token;
                    _graphServiceClient = new GraphServiceClient(
                        new DelegateAuthenticationProvider((requestMessage) =>
                        {
                            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                            return Task.CompletedTask;
                        }));

不确定是否需要申请类型权限,使用用户/{userID},但为什么不明白,获取错误:ME请求仅对委托认证流有效。

uemypmqf

uemypmqf1#

以下是使用委派权限和应用程序权限访问用户详细信息所需的权限:

至于此处注解中提到的for /me终点:

希望这个有用。

eufgjt7s

eufgjt7s2#

不确定是否需要申请类型权限,使用用户/{userID},但为什么不明白,获取错误:me请求仅对委派身份验证流有效
您正在定义委派权限,但在其中传递令牌。请查看以下文档:

首先让我澄清一下,什么时候需要委托权限。如果你想从你的应用程序访问UserList,它被称为应用程序权限,那么你需要传递auth令牌。但是如果你想在你需要委托权限的用户登录时访问UserList,那么就不需要传递auth令牌。因此,当你把它们混合在一起时,你会遇到这个特殊的错误。
拜托

权限验证提供程序:

根据您的方案,您可以使用多种身份验证协议调用Graph API。例如,授权代码流使本机应用程序和Web应用程序能够以用户的名义安全地获取令牌。您可以按如下方式实现:

var scopes = new[] { "User.Read" };

var tenantId = "common";

var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";

var authorizationCode = "AUTH_CODE_FROM_REDIRECT";

var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

var authCodeCredential = new AuthorizationCodeCredential(
    tenantId, clientId, clientSecret, authorizationCode, options);

var graphClient = new GraphServiceClient(authCodeCredential, scopes);

**注意:**更多详细信息请点击此处

使用图形SDK:

[Authorize]
public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly GraphServiceClient _graphServiceClient;
       

        public HomeController(ILogger<HomeController> logger,
                          GraphServiceClient graphServiceClient)
        {
            _logger = logger;
            _graphServiceClient = graphServiceClient;
        }
            
            [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
        public async Task<IActionResult> GetUsers()
        {

            var users = await _graphServiceClient
                       .Users
                       .Request()
                       .GetAsync()
                       .ConfigureAwait(false);

         
            return View();
        }
            
      }

**注意:**您可以check here

使用令牌获取服务:

//Initialize on behalf of user token aquisition service
            var _tokenAcquisition = this.HttpContext.RequestServices
           .GetRequiredService<ITokenAcquisition>() as ITokenAcquisition;
            //define the scope
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
       
            //Getting token from Azure Active Directory
            string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
            //Request Grap API end point
            HttpClient _client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.microsoft.com/v1.0/me"));
            //Passing Token For this Request
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response = await _client.SendAsync(request);
            //Get User into from grpah API
            dynamic userInfo = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

Program.cs配置:
您可以在这里查看详细信息。

string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
    
                
 services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
                    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                    .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                    .AddInMemoryTokenCaches();

**注意:**如果您仍需要更多信息,可以check our official document here.

相关问题