Challenge()始终重定向到登录页面

时间:2018-11-05 10:56:42

标签: asp.net asp.net-mvc asp.net-core-mvc

我正在尝试授权我的Action方法。一切正常,但是即使我已经登录,我的 Challenge()方法也始终重定向到登录页面。我尝试返回 Forbid()方法,它会重定向到 Access Denied 页面。 Challenge()方法可能是什么问题?

public async Task<IActionResult> Edit(int id)
{
     var project = await _context.Project.Include(p => p.OrganizationsLink).FirstOrDefaultAsync(p => p.Id == id);
     if (project == null)            
        return NotFound();

     //AUTHORIZATION
     var allowed = await _authz.AuthorizeAsync(User, null, new ProjectEditRequirement(project));
     if (!allowed.Succeeded)
        return Challenge();             

     return View(project);
}

1 个答案:

答案 0 :(得分:1)

对于Challenge,它受IAuthenticationService控制。 AuthenticationService将调用AuthenticateAsync来调用handler.AuthenticateAsync()

不确定您是否实现自定义IAuthenticationHandler,我将深入探讨CookieAuthenticationHandler

CookieAuthenticaiton的完整工作流程如下:

  • return Challenge(),用于Challenge

    public virtual ChallengeResult Challenge()
        => new ChallengeResult();
    
  • ChanllengeResult将呼叫ExecuteResultAsync

     public override async Task ExecuteResultAsync(ActionContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
    
        var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
        var logger = loggerFactory.CreateLogger<ChallengeResult>();
    
        logger.ChallengeResultExecuting(AuthenticationSchemes);
    
        if (AuthenticationSchemes != null && AuthenticationSchemes.Count > 0)
        {
            foreach (var scheme in AuthenticationSchemes)
            {
                await context.HttpContext.ChallengeAsync(scheme, Properties);
            }
        }
        else
        {
            await context.HttpContext.ChallengeAsync(Properties);
        }
    }
    
  • context.HttpContext.ChallengeAsync将调用ChallengeAsync

     public static Task ChallengeAsync(this HttpContext context, string scheme, AuthenticationProperties properties) =>
        context.RequestServices.GetRequiredService<IAuthenticationService>().ChallengeAsync(context, scheme, properties);
    
  • 对于CookieAuthenticationHandler

       protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
    {
        var redirectUri = properties.RedirectUri;
        if (string.IsNullOrEmpty(redirectUri))
        {
            redirectUri = OriginalPathBase + Request.Path + Request.QueryString;
        }
    
        var loginUri = Options.LoginPath + QueryString.Create(Options.ReturnUrlParameter, redirectUri);
        var redirectContext = new RedirectContext<CookieAuthenticationOptions>(Context, Scheme, Options, properties, BuildRedirectUri(loginUri));
        await Events.RedirectToLogin(redirectContext);
    }
    

您可能会发现,HandleChallengeAsync重定向操作。

根据我的选择,您可以尝试返回Forbid(),否则,您将需要覆盖HandleChallengeAsync