我正在使用Open ID connect混合流在ASP.NET MVC应用程序中获取访问令牌。并使用此访问令牌调用Power BI Rest API。但是,一旦访问令牌过期,REST API调用就会因为显而易见的原因而失败。
我的问题是,如何在不推送用户进行交互式登录的情况下获得新的访问令牌/刷新?
public void ConfigureAuth(IAppBuilder app)
{
try
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = redirectUri,
UseTokenLifetime = false,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
},
AuthorizationCodeReceived = OnAuthorizationCodeCallback
}
});
app.UseStageMarker(PipelineStage.Authenticate);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private static async Task OnAuthorizationCodeCallback(AuthorizationCodeReceivedNotification context)
{
var appConfidential = ConfidentialClientApplicationBuilder.Create(clientId)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
string powerBiPermissionApi = "https://analysis.windows.net/powerbi/api/";
string[] ReadUserWorkspaces = new string[] {
powerBiPermissionApi + "Workspace.Read.All",
powerBiPermissionApi + "Report.Read.All",
powerBiPermissionApi + "Dashboard.Read.All",
powerBiPermissionApi + "Dataset.Read.All"
};
var authResult = await appConfidential.AcquireTokenByAuthorizationCode(ReadUserWorkspaces, context.Code).ExecuteAsync();
ClaimsIdentity userClaims = context.AuthenticationTicket.Identity;
userClaims.AddClaim(new Claim("Access_Token", authResult.AccessToken));
}
发布于 2021-10-19 22:10:57
使用Azure Active Directory,我们可以为测量的天数指定自己的自定义超时/将会话长度与令牌有效性解耦。
我发现的一种方法是将会话持续时间与原始令牌的过期时间分开。通过向OIDC中间件提供以下选项,您可以告诉它停止在cookie中间件中控制此方面:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions {
...
UseTokenLifetime = false,
}
);
如果UseTokenLifetime
设置为false,cookie Middleware现在将遵循您在cookie Middleware参数中提供的任何设置。
或者,我们可以使用每5分钟更新一次的页面中的iFrame。
<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" id="refreshAuthenticationIframe" src="@Url.Action("CheckSessionTimeout", "Home", new { area = "" })" style="display:none;"></iframe>
您可以通过此Thread找到更多详细信息。
参考:
https://stackoverflow.com/questions/69615320
复制