How to plug method parameters into custom attribute

前端 未结 4 1076
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 08:13

I have a custom Attribute called AuthoriseAttribute whose constructor looks like this:

public AuthoriseAttribute(int userId)
{
  .. blah
}

This

4条回答
  •  执念已碎
    2021-02-19 09:08

    I was able to get around this by using the following:

    public class AuthorizeAttribute
    {
        protected bool RequireIdClaim { get; private set; }
    
        public AuthorizeAttribute(bool requireIdClaim = false)
        {
            RequireIdClaim = requireIdClaim;
        }
    
        public Authorize() 
        {
            //regular auth stuff here
    
            if (RequireIdClaim)
            {
                var routeData = context.ActionContext.Request.GetRouteData();
                var requiredIdClaim = Convert.ToInt32(routeData.Values["id"]); 
    
                //Check here if their user profile has a claim to that Id
            }
        }
    }
    

    And then on the specific methods you want to check Ids on,

    [HttpGet]
    [Route("{id}")]
    [Authorize(requireIdClaim: true)]
    public UserDetailsDto GetUserDetails(int userId)
    {
        .. blah
    }
    

    And if you don't care to check their Id, but just that they're authenticated

    [HttpGet]
    [Route("")]
    [Authorize]
    public bool isLoggedIn()
    {
        .. blah
    }
    

    Of course you can organize your authorize procedure however you like but this idea allows you to get their ID in your auth procedure there since it is passed in as route data. More here: https://stackoverflow.com/a/16054886

提交回复
热议问题