属性和自定义如何授权?



我正在尝试模拟[Authorize]属性,因为我发现您可以在整个类之上粘贴一个属性真是太神奇了,它以某种方式执行所有这些魔法来防止人们在类中运行方法,除非......东西。。。

我查找了创建自定义属性并找到了一些答案,基本上说除非我们使用反射,否则属性不可能阻止调用方法,因此我决定深入研究 Authorize 属性,但只能在元数据文件上找到"接口"方法,所以基本上

[Authorize]属性到底在做什么,我怎样才能实现属性来实际使用反射做事? 例如,当归因于类时,以下内容不执行任何操作:

[System.AttributeUsage(System.AttributeTargets.Class)]
public class Authorise : System.Attribute
{
public Authorise()
{
if (!SomeBoolCondition) throw new Exception ("Oh no!");
}
}

我无法理解授权属性如何进行检查,然后将程序重定向到登录页面。

如果要使用自定义属性实现自己的授权逻辑,还需要在请求管道中创建和注册中间件。您的中间件将接收整个 HttpContext,您可以使用它通过元数据检查端点中的 CustomAuthorizeAttribute。从那里,您可以实现授权逻辑,并决定继续使用"await next.Invoke((",或停止处理并向客户端返回未经授权的响应。

属性类:

[AttributeUsage(AttributeTargets.Class)]
public class CustomAuthorizeAttribute : Attribute
{
public IEnumerable<string> AllowedUserRoles { get; private set; }
public CustomAuthorizeAttribute(params string[] allowedUserRoles)
{
this.AllowedUserRoles = allowedUserRoles.AsEnumerable();
}
}

具有自定义属性的控制器:

[ApiController]
[Route("[controller]")]
[CustomAuthorize("Admin", "Supervisor", "Worker")]
public class WeatherForecastController : ControllerBase
{
}

启动。使用自定义中间件进行配置:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.Use(async (httpContext, next) =>
{
var endpointMetaData = httpContext.GetEndpoint()
.Metadata;
bool hasCustomAuthorizeAttribute = endpointMetaData.Any(x => x is CustomAuthorizeAttribute);
if (hasCustomAuthorizeAttribute)
{
// get the endpoint's instance of CustomAuthorizeAttribute
CustomAuthorizeAttribute customAuthorieAttribute = endpointMetaData
.FirstOrDefault(x => x is CustomAuthorizeAttribute) as CustomAuthorizeAttribute;
// here you will have access to customAuthorizeAttribute.AllowedUserRoles
// and can execute your custom logic with it
bool isAuthorized = true;
if (isAuthorized)
{
// continue processing the request
await next.Invoke();
}
else
{
// stop processing request and return unauthorized response
httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await httpContext.Response.WriteAsync("Unauthorized");
}
}
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

最新更新