gpt4 book ai didi

c# - 捕获失败的授权策略

转载 作者:行者123 更新时间:2023-11-30 12:38:48 24 4
gpt4 key购买 nike

在 .Net Core 2 中,假设有一个授权策略检查用户是否存在特定声明:

public class CompletedProfileRequirement : AuthorizationHandler<CompletedProfileRequirement>, IAuthorizationRequirement
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CompletedProfileRequirement requirement)
{
// Check that all required claims exist
if (/* invalid user claims */) {
context.Fail();
}

context.Succeed(requirement);
return Task.FromResult(0);
}
}

我们将策略检查放在 MVC Controller 之上:

[Authorize(Policy = "CompletedProfile")]
public class HomeController : Controller
{
// Controller stuff
}

我如何编写 IAuthorizationFilter 以便我们可以捕获此特定 CompletedProfileRequirement 策略的失败,以便我们可以将用户重定向到他们可以完成他们的页面简介?

最佳答案

根据authorization documentation ,可以从您的 AuthorizationHandler 访问 MVC 上下文:

Frameworks such as MVC or Jabbr are free to add any object to the Resource property on the AuthorizationHandlerContext to pass extra information.

For example, MVC passes an instance of AuthorizationFilterContext in the Resource property. This property provides access to HttpContext, RouteData, and everything else provided by MVC and Razor Pages.

因此,你可以这样做:

public class CompletedProfileRequirement : AuthorizationHandler<CompletedProfileRequirement>, IAuthorizationRequirement
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CompletedProfileRequirement requirement)
{
// Check that all required claims exist
if (/* invalid user claims */) {

// retrieve MVC context
if (context.Resource is AuthorizationFilterContext mvcContext)
{
// we still need to mark the requirement as succeeded,
// otherwise responde code is 401 unauthorized
context.Succeed(requirement);

// HTTP 302 temporary redirect to your page
mvcContext.HttpContext.Response.Redirect("/Home/Wherever", false);
return Task.FromResult(0);
}

}

context.Succeed(requirement);
return Task.FromResult(0);
}
}

关于c# - 捕获失败的授权策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49659485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com