簡體   English   中英

對 C# 中的每個請求強制 Azure 重新身份驗證

[英]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);
        }
    }
}

看來您希望重新驗證用戶的原因是即使存在 auth cookie 也要獲取/刷新內存中的令牌。 實現此目的的最簡單方法是使用AuthorizeForScopes屬性裝飾您的控制器。 您可以在此處查看Github上的示例項目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM