我正在尝试授权我的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);
}
答案 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);
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
。