gpt4 book ai didi

c# - 尝试连接到 Microsoft Graph 时出现 "Failed to acquire token silently"错误

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

我们有一个 asp.net MVC 应用程序,它使用 OpenID connect 针对 Azure AD 进行身份验证。用户在启动时使用以下代码进行身份验证:

public void ConfigureAuth(IAppBuilder app)
{
ApplicationDbContext db = new ApplicationDbContext();

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

app.UseCookieAuthentication(new CookieAuthenticationOptions());

app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ConfigHelper.ClientId,
Authority = ConfigHelper.Authority,
PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,

Notifications = new OpenIdConnectAuthenticationNotifications()
{
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.ClientSecret);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new ADALTokenCache(signedInUserID));
return authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId);
}
}
});
}

用户已成功通过身份验证,到目前为止一切顺利,但在应用程序的其他地方,我们正尝试使用来自帮助程序类的以下代码段来验证/连接到 Microsoft Graph:

ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.ClientSecret);
AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new ADALTokenCache(signedInUserID));
try
{
AuthenticationResult result = await authContext.AcquireTokenSilentAsync(ConfigHelper.GraphResourceId, cred, new UserIdentifier(signedInUserID, UserIdentifierType.UniqueId));
return result.AccessToken;
}
catch (AdalSilentTokenAcquisitionException e)
{
// handle exception
}

在这里,AcquireTokenSilentAsync 方法总是失败并显示以下内容:

Failed to acquire token silently as no token was found in the cache. Call method AcquireToken

Microsoft.IdentityModel.Clients.ActiveDirectory

at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenSilentHandler.SendTokenRequestAsync()
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.<CheckAndAcquireTokenUsingBrokerAsync>d__59.MoveNext()

在这两种情况下,都会通过调用 new ADALTokenCache(signedInUserID) 创建 TokenCache。 ADALTokenCache 类使用 Entity Framework 将 token 持久保存到 Azure SQL 服务器数据库。通过代码,我们看到在应用程序启动期间,ADALTokenCache 在调用 AcquireTokenByAuthorizationCodeAsync 时成功地存储并从数据库中读取,但是在调用 AcquireTokenSilentAsync 时 token 缓存返回 null,尽管所有变量都相同。

我们无法找到为什么它在第一种情况下会成功但在第二种情况下会失败。我们也无法确定它是否与 OWIN 相关、Graph 相关或 Entity Framework 相关。

或者对于这种情况,是否有比 OWIN 更适合的用户身份验证方法?

非常感谢任何帮助。

这是我们的 ADALTokenCache 类:

public class ADALTokenCache : TokenCache
{
private ApplicationDbContext db = new ApplicationDbContext();
private string userId;
private UserTokenCache Cache;

public ADALTokenCache(string signedInUserId)
{
// Associate the cache to the current user of the web app
userId = signedInUserId;
this.AfterAccess = AfterAccessNotification;
this.BeforeAccess = BeforeAccessNotification;
this.BeforeWrite = BeforeWriteNotification;
// Look up the entry in the database
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.WebUserUniqueId == userId);
// Place the entry in memory
this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.CacheBits, "ADALCache"));
}

// Clean up the database
public override void Clear()
{
base.Clear();
var cacheEntry = db.UserTokenCacheList.FirstOrDefault(c => c.WebUserUniqueId == userId);
db.UserTokenCacheList.Remove(cacheEntry);
db.SaveChanges();
}

// Notification raised before ADAL accesses the cache.
// This is your chance to update the in-memory copy from the DB, if the in-memory version is stale
void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
if (Cache == null)
{
// First time access
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.WebUserUniqueId == userId);
}
else
{
// Retrieve last write from the DB
var status = from e in db.UserTokenCacheList
where (e.WebUserUniqueId == userId)
select new
{
LastWrite = e.LastWrite
};

// If the in-memory copy is older than the persistent copy
if (status.First().LastWrite > Cache.LastWrite)
{
// Read from from storage, update in-memory copy
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.WebUserUniqueId == userId);
}
}
this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.CacheBits, "ADALCache"));
}

// Notification raised after ADAL accessed the cache.
// If the HasStateChanged flag is set, ADAL changed the content of the cache
void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// If state changed
if (this.HasStateChanged)
{
Cache = new UserTokenCache
{
WebUserUniqueId = userId,
CacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"),
LastWrite = DateTime.Now
};
// Update the DB and the lastwrite
db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified;
db.SaveChanges();
this.HasStateChanged = false;
}
}

void BeforeWriteNotification(TokenCacheNotificationArgs args)
{
// If you want to ensure that no concurrent write take place, use this notification to place a lock on the entry
}

public override void DeleteItem(TokenCacheItem item)
{
base.DeleteItem(item);
}
}

最佳答案

实际上从未深究这一点,但通过删除 visual studio 中的连接服务并再次添加 AAD 和 Graph 连接服务的身份验证,设法解决了这个问题。这当然用“干净”版本覆盖了一些项目文件,但似乎已经成功了。

感谢 juunas 4 的观看。

关于c# - 尝试连接到 Microsoft Graph 时出现 "Failed to acquire token silently"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331155/

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