Different API functionality for different roles











up vote
4
down vote

favorite












I have API with asp.net core 2.1. Claims-based authentication. Is it possible to combine these two api function in one?



[Authorize(Roles = "Admin")]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
_itemService.Delete(item.Id);
return Ok();
}

[Authorize]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
var id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
if (_itemService.IsAuthor(id))
{
_itemService.Delete(item.Id);
return Ok();
}
return Forbid();
}


Or should I just check the role inside method?










share|improve this question
























  • Resource-based authorization might be useful here.
    – Kirk Larkin
    Nov 7 at 8:59










  • May be having a custom policy with Authorization handler be the best choice in this case. docs.microsoft.com/en-us/aspnet/core/security/authorization/…
    – user2884707bond
    Nov 7 at 14:36















up vote
4
down vote

favorite












I have API with asp.net core 2.1. Claims-based authentication. Is it possible to combine these two api function in one?



[Authorize(Roles = "Admin")]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
_itemService.Delete(item.Id);
return Ok();
}

[Authorize]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
var id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
if (_itemService.IsAuthor(id))
{
_itemService.Delete(item.Id);
return Ok();
}
return Forbid();
}


Or should I just check the role inside method?










share|improve this question
























  • Resource-based authorization might be useful here.
    – Kirk Larkin
    Nov 7 at 8:59










  • May be having a custom policy with Authorization handler be the best choice in this case. docs.microsoft.com/en-us/aspnet/core/security/authorization/…
    – user2884707bond
    Nov 7 at 14:36













up vote
4
down vote

favorite









up vote
4
down vote

favorite











I have API with asp.net core 2.1. Claims-based authentication. Is it possible to combine these two api function in one?



[Authorize(Roles = "Admin")]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
_itemService.Delete(item.Id);
return Ok();
}

[Authorize]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
var id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
if (_itemService.IsAuthor(id))
{
_itemService.Delete(item.Id);
return Ok();
}
return Forbid();
}


Or should I just check the role inside method?










share|improve this question















I have API with asp.net core 2.1. Claims-based authentication. Is it possible to combine these two api function in one?



[Authorize(Roles = "Admin")]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
_itemService.Delete(item.Id);
return Ok();
}

[Authorize]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
var id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
if (_itemService.IsAuthor(id))
{
_itemService.Delete(item.Id);
return Ok();
}
return Forbid();
}


Or should I just check the role inside method?







c# asp.net-core asp.net-core-2.0






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 7 at 9:00









Kirk Larkin

17k33452




17k33452










asked Nov 7 at 8:55









Alexey Korsakov

678




678












  • Resource-based authorization might be useful here.
    – Kirk Larkin
    Nov 7 at 8:59










  • May be having a custom policy with Authorization handler be the best choice in this case. docs.microsoft.com/en-us/aspnet/core/security/authorization/…
    – user2884707bond
    Nov 7 at 14:36


















  • Resource-based authorization might be useful here.
    – Kirk Larkin
    Nov 7 at 8:59










  • May be having a custom policy with Authorization handler be the best choice in this case. docs.microsoft.com/en-us/aspnet/core/security/authorization/…
    – user2884707bond
    Nov 7 at 14:36
















Resource-based authorization might be useful here.
– Kirk Larkin
Nov 7 at 8:59




Resource-based authorization might be useful here.
– Kirk Larkin
Nov 7 at 8:59












May be having a custom policy with Authorization handler be the best choice in this case. docs.microsoft.com/en-us/aspnet/core/security/authorization/…
– user2884707bond
Nov 7 at 14:36




May be having a custom policy with Authorization handler be the best choice in this case. docs.microsoft.com/en-us/aspnet/core/security/authorization/…
– user2884707bond
Nov 7 at 14:36












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










For checking the permission with whether the user is Admin or Author, you could implement multiple requirements as the doc from @user2884707bond.



For using the multiple requrements for your scenario.



You could follow steps below:





  • PermissionHandler.cs



            public class PermissionHandler : IAuthorizationHandler
    {
    public Task HandleAsync(AuthorizationHandlerContext context)
    {
    var pendingRequirements = context.PendingRequirements.ToList();

    foreach (var requirement in pendingRequirements)
    {
    if (requirement is ReadPermission)
    {
    if (IsOwner(context.User, context.Resource) ||
    IsAdmin(context.User, context.Resource))
    {
    context.Succeed(requirement);
    }
    }
    else if (requirement is EditPermission ||
    requirement is DeletePermission)
    {
    if (IsOwner(context.User, context.Resource))
    {
    context.Succeed(requirement);
    }
    }
    }
    return Task.CompletedTask;
    }
    private bool IsAdmin(ClaimsPrincipal user, object resource)
    {
    if (user.IsInRole("Admin"))
    {
    return true;
    }
    return false;
    }

    private bool IsOwner(ClaimsPrincipal user, object resource)
    {
    // Code omitted for brevity

    return true;
    }

    private bool IsSponsor(ClaimsPrincipal user, object resource)
    {
    // Code omitted for brevity

    return true;
    }
    }



  • Requirements



        public class ReadPermission : IAuthorizationRequirement
    {
    // Code omitted for brevity
    }
    public class EditPermission : IAuthorizationRequirement
    {
    // Code omitted for brevity
    }
    public class DeletePermission : IAuthorizationRequirement
    {
    // Code omitted for brevity
    }



  • Register Requirement in Startup.cs



            services.AddAuthorization(options =>
    {
    options.AddPolicy("Read", policy => policy.AddRequirements(new ReadPermission()));
    });
    services.AddSingleton<IAuthorizationHandler, PermissionHandler>();



  • Use



     [Authorize(Policy = "Read")]
    [HttpPost("delete")]
    public IActionResult Delete([FromBody]Item item)
    {
    _itemService.Delete(item.Id);
    return Ok();
    }







share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53186143%2fdifferent-api-functionality-for-different-roles%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    For checking the permission with whether the user is Admin or Author, you could implement multiple requirements as the doc from @user2884707bond.



    For using the multiple requrements for your scenario.



    You could follow steps below:





    • PermissionHandler.cs



              public class PermissionHandler : IAuthorizationHandler
      {
      public Task HandleAsync(AuthorizationHandlerContext context)
      {
      var pendingRequirements = context.PendingRequirements.ToList();

      foreach (var requirement in pendingRequirements)
      {
      if (requirement is ReadPermission)
      {
      if (IsOwner(context.User, context.Resource) ||
      IsAdmin(context.User, context.Resource))
      {
      context.Succeed(requirement);
      }
      }
      else if (requirement is EditPermission ||
      requirement is DeletePermission)
      {
      if (IsOwner(context.User, context.Resource))
      {
      context.Succeed(requirement);
      }
      }
      }
      return Task.CompletedTask;
      }
      private bool IsAdmin(ClaimsPrincipal user, object resource)
      {
      if (user.IsInRole("Admin"))
      {
      return true;
      }
      return false;
      }

      private bool IsOwner(ClaimsPrincipal user, object resource)
      {
      // Code omitted for brevity

      return true;
      }

      private bool IsSponsor(ClaimsPrincipal user, object resource)
      {
      // Code omitted for brevity

      return true;
      }
      }



    • Requirements



          public class ReadPermission : IAuthorizationRequirement
      {
      // Code omitted for brevity
      }
      public class EditPermission : IAuthorizationRequirement
      {
      // Code omitted for brevity
      }
      public class DeletePermission : IAuthorizationRequirement
      {
      // Code omitted for brevity
      }



    • Register Requirement in Startup.cs



              services.AddAuthorization(options =>
      {
      options.AddPolicy("Read", policy => policy.AddRequirements(new ReadPermission()));
      });
      services.AddSingleton<IAuthorizationHandler, PermissionHandler>();



    • Use



       [Authorize(Policy = "Read")]
      [HttpPost("delete")]
      public IActionResult Delete([FromBody]Item item)
      {
      _itemService.Delete(item.Id);
      return Ok();
      }







    share|improve this answer

























      up vote
      1
      down vote



      accepted










      For checking the permission with whether the user is Admin or Author, you could implement multiple requirements as the doc from @user2884707bond.



      For using the multiple requrements for your scenario.



      You could follow steps below:





      • PermissionHandler.cs



                public class PermissionHandler : IAuthorizationHandler
        {
        public Task HandleAsync(AuthorizationHandlerContext context)
        {
        var pendingRequirements = context.PendingRequirements.ToList();

        foreach (var requirement in pendingRequirements)
        {
        if (requirement is ReadPermission)
        {
        if (IsOwner(context.User, context.Resource) ||
        IsAdmin(context.User, context.Resource))
        {
        context.Succeed(requirement);
        }
        }
        else if (requirement is EditPermission ||
        requirement is DeletePermission)
        {
        if (IsOwner(context.User, context.Resource))
        {
        context.Succeed(requirement);
        }
        }
        }
        return Task.CompletedTask;
        }
        private bool IsAdmin(ClaimsPrincipal user, object resource)
        {
        if (user.IsInRole("Admin"))
        {
        return true;
        }
        return false;
        }

        private bool IsOwner(ClaimsPrincipal user, object resource)
        {
        // Code omitted for brevity

        return true;
        }

        private bool IsSponsor(ClaimsPrincipal user, object resource)
        {
        // Code omitted for brevity

        return true;
        }
        }



      • Requirements



            public class ReadPermission : IAuthorizationRequirement
        {
        // Code omitted for brevity
        }
        public class EditPermission : IAuthorizationRequirement
        {
        // Code omitted for brevity
        }
        public class DeletePermission : IAuthorizationRequirement
        {
        // Code omitted for brevity
        }



      • Register Requirement in Startup.cs



                services.AddAuthorization(options =>
        {
        options.AddPolicy("Read", policy => policy.AddRequirements(new ReadPermission()));
        });
        services.AddSingleton<IAuthorizationHandler, PermissionHandler>();



      • Use



         [Authorize(Policy = "Read")]
        [HttpPost("delete")]
        public IActionResult Delete([FromBody]Item item)
        {
        _itemService.Delete(item.Id);
        return Ok();
        }







      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        For checking the permission with whether the user is Admin or Author, you could implement multiple requirements as the doc from @user2884707bond.



        For using the multiple requrements for your scenario.



        You could follow steps below:





        • PermissionHandler.cs



                  public class PermissionHandler : IAuthorizationHandler
          {
          public Task HandleAsync(AuthorizationHandlerContext context)
          {
          var pendingRequirements = context.PendingRequirements.ToList();

          foreach (var requirement in pendingRequirements)
          {
          if (requirement is ReadPermission)
          {
          if (IsOwner(context.User, context.Resource) ||
          IsAdmin(context.User, context.Resource))
          {
          context.Succeed(requirement);
          }
          }
          else if (requirement is EditPermission ||
          requirement is DeletePermission)
          {
          if (IsOwner(context.User, context.Resource))
          {
          context.Succeed(requirement);
          }
          }
          }
          return Task.CompletedTask;
          }
          private bool IsAdmin(ClaimsPrincipal user, object resource)
          {
          if (user.IsInRole("Admin"))
          {
          return true;
          }
          return false;
          }

          private bool IsOwner(ClaimsPrincipal user, object resource)
          {
          // Code omitted for brevity

          return true;
          }

          private bool IsSponsor(ClaimsPrincipal user, object resource)
          {
          // Code omitted for brevity

          return true;
          }
          }



        • Requirements



              public class ReadPermission : IAuthorizationRequirement
          {
          // Code omitted for brevity
          }
          public class EditPermission : IAuthorizationRequirement
          {
          // Code omitted for brevity
          }
          public class DeletePermission : IAuthorizationRequirement
          {
          // Code omitted for brevity
          }



        • Register Requirement in Startup.cs



                  services.AddAuthorization(options =>
          {
          options.AddPolicy("Read", policy => policy.AddRequirements(new ReadPermission()));
          });
          services.AddSingleton<IAuthorizationHandler, PermissionHandler>();



        • Use



           [Authorize(Policy = "Read")]
          [HttpPost("delete")]
          public IActionResult Delete([FromBody]Item item)
          {
          _itemService.Delete(item.Id);
          return Ok();
          }







        share|improve this answer












        For checking the permission with whether the user is Admin or Author, you could implement multiple requirements as the doc from @user2884707bond.



        For using the multiple requrements for your scenario.



        You could follow steps below:





        • PermissionHandler.cs



                  public class PermissionHandler : IAuthorizationHandler
          {
          public Task HandleAsync(AuthorizationHandlerContext context)
          {
          var pendingRequirements = context.PendingRequirements.ToList();

          foreach (var requirement in pendingRequirements)
          {
          if (requirement is ReadPermission)
          {
          if (IsOwner(context.User, context.Resource) ||
          IsAdmin(context.User, context.Resource))
          {
          context.Succeed(requirement);
          }
          }
          else if (requirement is EditPermission ||
          requirement is DeletePermission)
          {
          if (IsOwner(context.User, context.Resource))
          {
          context.Succeed(requirement);
          }
          }
          }
          return Task.CompletedTask;
          }
          private bool IsAdmin(ClaimsPrincipal user, object resource)
          {
          if (user.IsInRole("Admin"))
          {
          return true;
          }
          return false;
          }

          private bool IsOwner(ClaimsPrincipal user, object resource)
          {
          // Code omitted for brevity

          return true;
          }

          private bool IsSponsor(ClaimsPrincipal user, object resource)
          {
          // Code omitted for brevity

          return true;
          }
          }



        • Requirements



              public class ReadPermission : IAuthorizationRequirement
          {
          // Code omitted for brevity
          }
          public class EditPermission : IAuthorizationRequirement
          {
          // Code omitted for brevity
          }
          public class DeletePermission : IAuthorizationRequirement
          {
          // Code omitted for brevity
          }



        • Register Requirement in Startup.cs



                  services.AddAuthorization(options =>
          {
          options.AddPolicy("Read", policy => policy.AddRequirements(new ReadPermission()));
          });
          services.AddSingleton<IAuthorizationHandler, PermissionHandler>();



        • Use



           [Authorize(Policy = "Read")]
          [HttpPost("delete")]
          public IActionResult Delete([FromBody]Item item)
          {
          _itemService.Delete(item.Id);
          return Ok();
          }








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 8 at 5:17









        Tao Zhou

        3,62721026




        3,62721026






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53186143%2fdifferent-api-functionality-for-different-roles%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()