gpt4 book ai didi

c# - 如何在 ASP.NET Core 中覆盖 HandleUnauthorizedRequest

转载 作者:行者123 更新时间:2023-12-05 05:22:29 25 4
gpt4 key购买 nike

我正在将我的项目迁移到 asp.net core,但我一直在为我的 Controller 迁移我的 CustomAuthorization 属性。这是我的代码。

public class CustomAuthorization : AuthorizeAttribute
{
public string Url { get; set; }

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery);
}
else if (!Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
{
filterContext.Result = new ViewResult
{
ViewName = "AcessDenied"
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}

然后我将它用于我的 Controller

[CustomAuthorization(Url = "/Admin/Account/Login", Roles = "Admin")]
public abstract class AdminController : Controller { }

所以,基本上我可以在不满足角色时使用它重定向到不同的登录页面。我的区域很少,每个区域都有不同的登录页面。我试过像这样使用 CookieAuthenticationOptions

services.Configure<CookieAuthenticationOptions>(options =>
{
options.AuthenticationScheme = "Admin";
options.LoginPath = "/Admin/Account/Login";
});

然后在我的管理 Controller 上

[Area("Admin")]
[Authorize(ActiveAuthenticationSchemes = "Admin", Roles = "Admin")]

但是我登录后还是进不去

最佳答案

我正在我的一个项目中做类似的事情。这个答案没有使用 AuthorizeAttribute;但它可能会帮助某些人通过谷歌搜索登陆这里。在我的例子中,我使用它来根据自定义逻辑进行授权。

首先是我的自定义属性类:

public class CustomAuthorizationAttribute : ActionFilterAttribute
{
private readonly IMyDepedency _dp;
public CustomAuthorizationAttribute(IMyDepedency dp)
{
_dp = dp;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var isValid = false;
//write my validation and authorization logic here
if(!isValid)
{
var unauthResult = new UnauthorizedResult();

context.Result = unauthResult;
}

base.OnActionExecuting(context);
}
}

我这样装饰我的 Controller :

[ServiceFilter(typeof (CustomAuthorizationAttribute))]

然后在我的 Startup 类中

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();

// my other stuff that is not relevant in this post

// Security
services.AddTransient<CustomAuthorizationAttribute>();
}

关于c# - 如何在 ASP.NET Core 中覆盖 HandleUnauthorizedRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446028/

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