【问题标题】:Force Azure Re-Authentication for each request in C#对 C# 中的每个请求强制进行 Azure 重新身份验证
【发布时间】:2020-05-14 16:38:10
【问题描述】:

我有一个要求,我想为 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,
});

【问题讨论】:

  • 嗨@DCZ。您能解释一下为什么需要这样做吗?为什么您不能使用作为身份验证结果颁发的访问令牌,只要它没有过期?

标签: c# azure asp.net-web-api azure-ad-b2c


【解决方案1】:

根据你之前发布的代码和案例,我认为不是Azure ad b2c,所以在这里我将回复azure ad。

当您请求授权码时,有一个prompt=login 属性表示应提示用户重新进行身份验证

这里还有一篇关于Forcing reauthentication with 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);
        }
    }
}

【讨论】:

    【解决方案2】:

    您希望重新对用户进行身份验证的原因似乎是即使存在身份验证 cookie 时也要获取/刷新内存中的令牌。实现这一点的最简单方法是使用 AuthorizeForScopes 属性装饰您的控制器。您可以在Github here查看示例项目

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      相关资源
      最近更新 更多