Custom authorization attribute in .NET Core [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-12-21 12:14:24

问题


I'm building an API in .NET Core 1.1. I build a custom User object from HttpContext.User in a base controller that all of my other controllers inherit from, and I have authentication enabled by default (must be manually disabled with [AllowAnonymous] when necessary). The User object has an IsAdmin property. Right now I'm checking if the user is an admin at the top of each relevant function like below, but I feel like there must be a way to add a custom attribute to simplify and clean up this code.

For reference, User.IsAdmin is shorthand for this:

bool.Parse(HttpContext.User.FindFirst("IsAdmin")?.Value)

Instead of this:

[HttpGet]
public async Task<IActionResult> Get()
{
    if (!User.IsAdmin)
        return Forbid();

    // logic
}

I'd like this (or something similar):

[AdminOnly]
[HttpGet]
public async Task<IActionResult> Get()
{
    // logic
}

I tried looking at the source for [AuthorizeAttribute] to try to build from, but it's just a shell and I don't know where the real magic happens.

How can I accomplish this?


回答1:


The solution suggested by @JoeAudette seems to be the best option.


Create your own policy in Startup.cs ConfigureServices():

services.AddAuthorization(options => 
    options.AddPolicy("PolicyName", p =>
    {
        p.RequireAuthenticatedUser();
        p.RequireClaim("IsAdmin", true); <- your criteria here (claim type, claim value) ???
        p.Build();
    })
);


Then just use it as an attribute:

[Authorize("PolicyName")]


来源:https://stackoverflow.com/questions/41526086/custom-authorization-attribute-in-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!