我們有一個ASP.NET MVC 5 web應用程序,我們使用AngularJS從MVC控制器(不是ApiControllers)獲取數據。它的身份驗證使用cookie身份驗證與默認的到期時間1小時後連接到Azure AD。當ajax調用失敗時在後端更新訪問令牌
該應用程序是SPA。一旦用戶登錄,他們不會導航到其他頁面,而只使用ajax($ http)調用。
到目前爲止,我們擴展了Startup.Configuration()中的RedirectToIdentityProvider方法,以識別ajax調用,並在令牌過期時將錯誤403返回給客戶端。這樣,我們避免重定向到權威頁面並獲得CORS錯誤。
此外,我們在同一類的AuthorizationCodeReceived
中實現了持久令牌緩存助手TokenCache
(命名空間Microsoft.IdentityModel.Clients.ActiveDirectory
)。
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ConfigurationHelper.ClientId,
Authority = ConfigurationHelper.AzureAdAuthorizationUri,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(ConfigurationHelper.ClientId, ConfigurationHelper.AppKey);
String UserObjectId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(ConfigurationHelper.AzureAdAuthorizationUri, new InMemoryTokenCache(UserObjectId));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigurationHelper.AzureAdGraphResourceUri);
return Task.FromResult(0);
},
RedirectToIdentityProvider = (context) =>
{
if (IsAjaxRequest(context.Request))
{
context.Response.StatusCode = 401; // for web API only!
context.Response.Headers.Remove("Set-Cookie");
context.State = NotificationResultState.HandledResponse;
}
else
{
string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
context.ProtocolMessage.RedirectUri = appBaseUrl + "/" + context.Request.QueryString;
context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
}
return Task.FromResult(0);
},
AuthenticationFailed = (context) =>
{
// Suppress the exception
context.HandleResponse();
return Task.FromResult(0);
}
}
});
}
InMemoryTokenCache
是我們的包裝器TokenCache
IsAjaxRequest
是識別Ajax調用的函數。其餘的都是ASP.NET MVC 5模板的標準。
我們的問題是,當用戶訪問令牌到期時,我們要刷新它,並繼續使用,無需將用戶重定向到一個登錄屏幕或返回403客戶端去。我們在哪裏以及如何做到這一點?
這是一個選項,但該理論認爲我不應該這樣做。刷新令牌僅用於獲取訪問令牌,並且僅在用戶稍後過期後請求某些內容。 –
我已經添加了另一個解決方案,希望它有幫助;) –