[英]Force Azure Re-Authentication for each request in C#
我有一個要求,我想為 Web API 中的每個請求獲取Azure
登錄的授權代碼。 截至目前,一旦用戶登錄到 Azure,之后我將無法獲得授權代碼,因為用戶已經登錄。如何強制用戶再次登錄? 這是我目前在web API
的 owin_startup 文件中使用的代碼?
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieSecure = (CookieSecureOption)Convert.ToInt32(cookieSecure), // CookieSecureOption.NeverAlways
CookieManager = new SystemWebCookieManager(),
CookieHttpOnly = false,
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
RedirectUri = RedirectUri,
});
根據你之前發的代碼和案例,我認為不是Azure ad b2c的問題,所以在這里我對azure ad進行回復。
當您請求授權碼時,有一個prompt=login
屬性,表示應提示用戶重新進行身份驗證。
這里還有一篇關於使用 Azure AD 強制重新身份驗證的文章,建議使用Token Max Age來實現它。
您可以將 max_age= 附加到授權 URL(或者只輸入 0 以始終強制進行密碼驗證)。 因此,一旦用戶被重定向到 URL,他們將看到重新登錄的信息。
public class RequireReauthenticationAttribute : Attribute, IAsyncResourceFilter
{
private int _timeElapsedSinceLast;
public RequireReauthenticationAttribute(int timeElapsedSinceLast)
{
_timeElapsedSinceLast = timeElapsedSinceLast;
}
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
var foundAuthTime = int.TryParse(context.HttpContext.User.FindFirst(AppClaimTypes.AuthTime)?.Value, out int authTime);
if (foundAuthTime && DateTime.UtcNow.ToUnixTimestamp() - authTime < _timeElapsedSinceLast)
{
await next();
}
else
{
var state = new Dictionary<string, string> { { "reauthenticate", "true" } };
await context.HttpContext.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties(state)
{
RedirectUri = context.HttpContext.Request.Path
}, ChallengeBehavior.Unauthorized);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.