我在使用Microsoft Graph API時遇到了問題。在 System.Private.CoreLib.dll「Microsoft.Graph.ServiceException」:每當我試圖得到一個日曆,我得到了以下錯誤消息:Microsoft.Graph.ServiceException'代碼:BadRequest消息:當前已認證的上下文對此請求無效
拋出異常「代碼:錯誤請求消息:經認證的當前 上下文是無效申請
起初,我還以爲是類似this職位,但我的用戶進行身份驗證,所以我相信這是不是這樣的。
這裏是我的代碼:
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應用程序註冊門戶網站,和我得到令牌時我要求它,所以我不知道什麼可能會造成問題。
我以爲我是這麼做的。我已經在openid選項中將Authority地址更改爲'https://login.microsoftonline.com/common/v2.0/authorize ?,並將CCA中'OnAuthorizationCodeReceived'事件的權限地址更改爲https: // login.microsoftonline.com/common/v2.0/token',但我仍然收到相同的錯誤消息。當我改變了openId權限時,我必須分別添加元數據地址,如'https:// login.microsoftonline.com/common/v2.0/.well-known/openid-configuration' –
您正在使用'ConfidentialClientApplication '這是客戶端證書流程。查看https://docs.microsoft.com/en-us/azure/active-directory/develop/guidedsetups/active-directory-windesktop查看使用'PublicClientApplication'的例子 –
使用OpenID connect有什麼意義使用PublicClientApplication?我認爲現在有方法可以使用授權碼獲取訪問令牌。或者我應該使用另一種類型的OpenId事件? –