繁体   English   中英

Microsoft.Graph.ServiceException' 代码:BadRequest 消息:当前经过身份验证的上下文对此请求无效

[英]Microsoft.Graph.ServiceException' Code: BadRequest Message: Current authenticated context is not valid for this request

我在使用 Microsoft Graph API 时遇到了问题。 每当我尝试获取日历时,都会收到以下错误消息:

抛出异常:System.Private.CoreLib.dll 中的“Microsoft.Graph.ServiceException”:“代码:BadRequest 消息:当前经过身份验证的上下文对此请求无效”

一开始我以为和这个帖子差不多,但是我的用户是经过身份验证的,所以我认为不是这样。

这是我的代码:

EventController.cs

public async Task<Calendar> GetEventInfoAsync()
    {
        var accessToken = await getAcessTokenAsync();
        DelegateAuthenticationProvider delegateAuthenticationProvider = new DelegateAuthenticationProvider(
            (requestMessage) => 
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                return Task.FromResult(0);
            }
        );
        GraphServiceClient graphClient = new GraphServiceClient(delegateAuthenticationProvider);
        var calendar = await graphClient.Me.Calendar.Request().GetAsync();
        return calendar;
    }

这就是我获取访问令牌的方式:

public async Task<string> getAcessTokenAsync()
    {
        if(User.Identity.IsAuthenticated)
        {
            var userId = User.FindFirst("MicrosoftUserId")?.Value;
            ConfidentialClientApplication cca =
                new ConfidentialClientApplication( Configuration["MicrosoftAuth:ClientId"],
                                                    String.Format(System.Globalization.CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}{1}", "common", "/v2.0"),
                                                    Configuration["MicrosoftAuth:RedirectUri"]+ "signin-oidc", 
                                                    new Microsoft.Identity.Client.ClientCredential(Configuration["MicrosoftAuth:ClientSecret"]),
                                                    new SessionTokenCache(userId,_memoryCache).GetCacheInstance(),
                                                    null);               
            var token = await cca.AcquireTokenForClientAsync(new string[]{"https://graph.microsoft.com/.default"});
            return token.AccessToken;
        }
        else
            throw new Exception("User is not autenticated");
    }

最后,这是身份验证选项在启动文件中的外观。

services.AddAuthentication().AddOpenIdConnect(openIdOptions => 
        {
            openIdOptions.ResponseType = OpenIdConnectResponseType.CodeIdToken;
            openIdOptions.Authority = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}{1}", "common", "/v2.0");
            openIdOptions.ClientId = Configuration["MicrosoftAuth:ClientId"];
            openIdOptions.ClientSecret = Configuration["MicrosoftAuth:ClientSecret"];
            openIdOptions.SaveTokens = true;
            openIdOptions.TokenValidationParameters = new TokenValidationParameters{
                ValidateIssuer = false
            };
            var scopes = Configuration["MicrosoftAuth:Scopes"].Split(' ');
                foreach (string scope in scopes){
                    openIdOptions.Scope.Add(scope);
            }
            openIdOptions.Events = new OpenIdConnectEvents{
                OnAuthorizationCodeReceived = async (context) =>
                {   
                    var userId = context.Principal.Claims.First(item => item.Type == ObjectIdentifierType).Value;
                    IMemoryCache memoryCache = context.HttpContext.RequestServices.GetRequiredService<IMemoryCache>();
                    ConfidentialClientApplication cca =
                        new ConfidentialClientApplication( Configuration["MicrosoftAuth:ClientId"],
                                                            String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}{1}{2}", "common", "/v2.0", "/adminconsent"),
                                                            Configuration["MicrosoftAuth:RedirectUri"]+ "signin-oidc", 
                                                            new Microsoft.Identity.Client.ClientCredential(Configuration["MicrosoftAuth:ClientSecret"]),
                                                            new SessionTokenCache(userId,memoryCache).GetCacheInstance(),
                                                            null);
                    var code = context.ProtocolMessage.Code;                        
                    var result = await cca.AcquireTokenByAuthorizationCodeAsync(code,new string[]{"User.Read.All", "Calendars.ReadWrite"});
                    context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                },
            };
        });

我的应用程序已在 Microsoft 应用程序注册门户中注册,并且在我请求令牌时确实获得了令牌,因此我不确定可能是什么原因导致了问题。

与预览线程相同的问题。 Azure AD 颁发的令牌有两种,使用委托或应用。 您获得的令牌正在使用委托给应用程序的客户端凭据流。 当您请求使用这种令牌时没有me上下文(请参阅代表用户获取访问权限和在没有用户的情况下获取访问权限以了解区别)。

要将 Microsoft Graph 与 Web 应用程序集成并委托用户调用 Microsoft Graph,您需要在startup.cs文件中配置时使用代码授权流OnAuthorizationCodeReceived事件)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM