在ASP.Net MVC C#中,如果在缓存中未找到令牌,无法静默获取令牌,你可以调用AcquireToken方法来解决。下面是一个示例代码:
using System;
using Microsoft.Identity.Client;
namespace YourNamespace
{
public class YourClassName
{
private static string clientId = "YourClientId";
private static string clientSecret = "YourClientSecret";
private static string authority = "YourAuthority";
private static string[] scopes = { "YourScope" };
public async Task GetAccessToken()
{
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
try
{
var authenticationResult = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
return authenticationResult.AccessToken;
}
catch (Exception ex)
{
// 处理异常
throw ex;
}
}
}
}
在上面的示例代码中,你需要替换以下变量的值:
YourClientId
:你的应用程序的客户端ID。YourClientSecret
:你的应用程序的客户端密钥。YourAuthority
:你的租户的授权URL。YourScope
:你想要获取的访问令牌的范围。通过调用AcquireTokenForClient
方法,你可以获取访问令牌来访问所需的资源。如果在缓存中未找到令牌,它将发出身份验证请求以获取新的令牌。