How do you create a custom AuthorizeAttribute in ASP.NET Core?

前端 未结 11 1224
春和景丽
春和景丽 2020-11-21 17:19

I\'m trying to make a custom authorization attribute in ASP.NET Core. In previous versions it was possible to override bool AuthorizeCore(HttpContextBase httpContext)

相关标签:
11条回答
  • 2020-11-21 18:09

    As of this writing I believe this can be accomplished with the IClaimsTransformation interface in asp.net core 2 and above. I just implemented a proof of concept which is sharable enough to post here.

    public class PrivilegesToClaimsTransformer : IClaimsTransformation
    {
        private readonly IPrivilegeProvider privilegeProvider;
        public const string DidItClaim = "http://foo.bar/privileges/resolved";
    
        public PrivilegesToClaimsTransformer(IPrivilegeProvider privilegeProvider)
        {
            this.privilegeProvider = privilegeProvider;
        }
    
        public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            if (principal.Identity is ClaimsIdentity claimer)
            {
                if (claimer.HasClaim(DidItClaim, bool.TrueString))
                {
                    return principal;
                }
    
                var privileges = await this.privilegeProvider.GetPrivileges( ... );
                claimer.AddClaim(new Claim(DidItClaim, bool.TrueString));
    
                foreach (var privilegeAsRole in privileges)
                {
                    claimer.AddClaim(new Claim(ClaimTypes.Role /*"http://schemas.microsoft.com/ws/2008/06/identity/claims/role" */, privilegeAsRole));
                }
            }
    
            return principal;
        }
    }
    

    To use this in your Controller just add an appropriate [Authorize(Roles="whatever")] to your methods.

    [HttpGet]
    [Route("poc")]
    [Authorize(Roles = "plugh,blast")]
    public JsonResult PocAuthorization()
    {
        var result = Json(new
        {
            when = DateTime.UtcNow,
        });
    
        result.StatusCode = (int)HttpStatusCode.OK;
    
        return result;
    }
    

    In our case every request includes an Authorization header that is a JWT. This is the prototype and I believe we will do something super close to this in our production system next week.

    Future voters, consider the date of writing when you vote. As of today, this works on my machine.™ You will probably want more error handling and logging on your implementation.

    0 讨论(0)
  • 2020-11-21 18:11

    Based on Derek Greer GREAT answer, i did it with enums.

    Here is an example of my code:

    public enum PermissionItem
    {
        User,
        Product,
        Contact,
        Review,
        Client
    }
    
    public enum PermissionAction
    {
        Read,
        Create,
    }
    
    
    public class AuthorizeAttribute : TypeFilterAttribute
    {
        public AuthorizeAttribute(PermissionItem item, PermissionAction action)
        : base(typeof(AuthorizeActionFilter))
        {
            Arguments = new object[] { item, action };
        }
    }
    
    public class AuthorizeActionFilter : IAuthorizationFilter
    {
        private readonly PermissionItem _item;
        private readonly PermissionAction _action;
        public AuthorizeActionFilter(PermissionItem item, PermissionAction action)
        {
            _item = item;
            _action = action;
        }
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            bool isAuthorized = MumboJumboFunction(context.HttpContext.User, _item, _action); // :)
    
            if (!isAuthorized)
            {
                context.Result = new ForbidResult();
            }
        }
    }
    
    public class UserController : BaseController
    {
        private readonly DbContext _context;
    
        public UserController( DbContext context) :
            base()
        {
            _logger = logger;
        }
    
        [Authorize(PermissionItem.User, PermissionAction.Read)]
        public async Task<IActionResult> Index()
        {
            return View(await _context.User.ToListAsync());
        }
    }
    
    0 讨论(0)
  • 2020-11-21 18:11

    What is the current approach to make a custom AuthorizeAttribute

    Easy: don't create your own AuthorizeAttribute.

    For pure authorization scenarios (like restricting access to specific users only), the recommended approach is to use the new authorization block: https://github.com/aspnet/MusicStore/blob/1c0aeb08bb1ebd846726232226279bbe001782e1/samples/MusicStore/Startup.cs#L84-L92

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AuthorizationOptions>(options =>
            {
                options.AddPolicy("ManageStore", policy => policy.RequireClaim("Action", "ManageStore"));
            });
        }
    }
    
    public class StoreController : Controller
    {
        [Authorize(Policy = "ManageStore"), HttpGet]
        public async Task<IActionResult> Manage() { ... }
    }
    

    For authentication, it's best handled at the middleware level.

    What are you trying to achieve exactly?

    0 讨论(0)
  • 2020-11-21 18:14

    The modern way is AuthenticationHandlers

    in startup.cs add

    services.AddAuthentication("BasicAuthentication").AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
    
    public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
        {
            private readonly IUserService _userService;
    
            public BasicAuthenticationHandler(
                IOptionsMonitor<AuthenticationSchemeOptions> options,
                ILoggerFactory logger,
                UrlEncoder encoder,
                ISystemClock clock,
                IUserService userService)
                : base(options, logger, encoder, clock)
            {
                _userService = userService;
            }
    
            protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
            {
                if (!Request.Headers.ContainsKey("Authorization"))
                    return AuthenticateResult.Fail("Missing Authorization Header");
    
                User user = null;
                try
                {
                    var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                    var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                    var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
                    var username = credentials[0];
                    var password = credentials[1];
                    user = await _userService.Authenticate(username, password);
                }
                catch
                {
                    return AuthenticateResult.Fail("Invalid Authorization Header");
                }
    
                if (user == null)
                    return AuthenticateResult.Fail("Invalid User-name or Password");
    
                var claims = new[] {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Username),
                };
                var identity = new ClaimsIdentity(claims, Scheme.Name);
                var principal = new ClaimsPrincipal(identity);
                var ticket = new AuthenticationTicket(principal, Scheme.Name);
    
                return AuthenticateResult.Success(ticket);
            }
        }
    

    IUserService is a service that you make where you have user name and password. basically it returns a user class that you use to map your claims on.

    var claims = new[] {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Username),
                }; 
    

    Then you can query these claims and her any data you mapped, ther are quite a few, have a look at ClaimTypes class

    you can use this in an extension method an get any of the mappings

    public int? GetUserId()
    {
       if (context.User.Identity.IsAuthenticated)
        {
           var id=context.User.FindFirst(ClaimTypes.NameIdentifier);
           if (!(id is null) && int.TryParse(id.Value, out var userId))
                return userId;
         }
          return new Nullable<int>();
     }
    

    This new way, i think is better than the old way as shown here, both work

    public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization != null)
            {
                var authToken = actionContext.Request.Headers.Authorization.Parameter;
                // decoding authToken we get decode value in 'Username:Password' format
                var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
                // spliting decodeauthToken using ':'
                var arrUserNameandPassword = decodeauthToken.Split(':');
                // at 0th postion of array we get username and at 1st we get password
                if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))
                {
                    // setting current principle
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(arrUserNameandPassword[0]), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }
    
        public static bool IsAuthorizedUser(string Username, string Password)
        {
            // In this method we can handle our database logic here...
            return Username.Equals("test") && Password == "test";
        }
    }
    
    0 讨论(0)
  • 2020-11-21 18:16

    I'm the asp.net security person. Firstly let me apologize that none of this is documented yet outside of the music store sample or unit tests, and it's all still being refined in terms of exposed APIs. Detailed documentation is here.

    We don't want you writing custom authorize attributes. If you need to do that we've done something wrong. Instead, you should be writing authorization requirements.

    Authorization acts upon Identities. Identities are created by authentication.

    You say in comments you want to check a session ID in a header. Your session ID would be the basis for identity. If you wanted to use the Authorize attribute you'd write an authentication middleware to take that header and turn it into an authenticated ClaimsPrincipal. You would then check that inside an authorization requirement. Authorization requirements can be as complicated as you like, for example here's one that takes a date of birth claim on the current identity and will authorize if the user is over 18;

    public class Over18Requirement : AuthorizationHandler<Over18Requirement>, IAuthorizationRequirement
    {
            public override void Handle(AuthorizationHandlerContext context, Over18Requirement requirement)
            {
                if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
                {
                    context.Fail();
                    return;
                }
    
                var dateOfBirth = Convert.ToDateTime(context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value);
                int age = DateTime.Today.Year - dateOfBirth.Year;
                if (dateOfBirth > DateTime.Today.AddYears(-age))
                {
                    age--;
                }
    
                if (age >= 18)
                {
                    context.Succeed(requirement);
                }
                else
                {
                    context.Fail();
                }
            }
        }
    }
    

    Then in your ConfigureServices() function you'd wire it up

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Over18", 
            policy => policy.Requirements.Add(new Authorization.Over18Requirement()));
    });
    

    And finally, apply it to a controller or action method with

    [Authorize(Policy = "Over18")]
    
    0 讨论(0)
提交回复
热议问题