Custom authorization requirement and handler example in asp net core

Поделиться
HTML-код
  • Опубликовано: 9 окт 2024

Комментарии • 53

  • @swimmorning
    @swimmorning 4 года назад +15

    Sir Venkat,
    In Asp.Net Core 3.0 the following always returns null, do you know the reason?
    var authFilterContext = context.Resource as AuthorizationFilterContext
    I had to make it work by first injecting IHttpContextAccessor in the Handler class
    private readonly IHttpContextAccessor contextAccessor;
    public CanEditOnlyOtherAdminRolesAndClaimsHandler(IHttpContextAccessor contextAccessor)
    {
    this.contextAccessor = contextAccessor;
    }
    then Access the httpContext:
    string adminIdBeingEdited = contextAccessor.HttpContext.Request.Query["userId"];
    Finally register the services:
    services.AddHttpContextAccessor();

    • @get_ready
      @get_ready 4 года назад

      Cheers good sir

    • @cristina_machado
      @cristina_machado 4 года назад

      Hello! Can you explain better where did you put the code? I tried but it did not work for me. Thank you.

    • @get_ready
      @get_ready 4 года назад

      @@cristina_machado constructor and private field in our custom handler class, then in the same class in handle method you access the httpcontext, and the service (last line) is registered in startup file

    • @cristina_machado
      @cristina_machado 4 года назад +7

      @@get_ready Hello again!
      Now it works perfectly, I had to make a search and I found
      stackoverflow.com/questions/58565574/reading-the-authorizationfiltercontext-in-netcore-api-3-1
      and here is my code to help others:
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Http;
      using System.Linq;
      using System.Security.Claims;
      using System.Threading.Tasks;
      namespace ReportWeb.Security
      {
      public class CanEditOnlyOtherAdminRolesAndClaimsHandler : AuthorizationHandler
      {
      private readonly IHttpContextAccessor httpContextAccessor;
      public CanEditOnlyOtherAdminRolesAndClaimsHandler(IHttpContextAccessor httpContextAccessor)
      {
      this.httpContextAccessor = httpContextAccessor;
      }
      protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
      ManageAdminRolesAndClaimsRequirement requirement)
      {
      var authFilterContext = httpContextAccessor.HttpContext;
      if (authFilterContext == null)
      {
      return Task.CompletedTask;
      }
      string loggedInAdminId =
      context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
      string adminIdBeingEdited = httpContextAccessor.HttpContext.Request.Query["userId"];
      if (context.User.IsInRole("Admin") &&
      context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") &&
      adminIdBeingEdited.ToLower() != loggedInAdminId.ToLower())
      {
      context.Succeed(requirement);
      }
      return Task.CompletedTask;
      }
      }
      }

    • @conaxlearn8566
      @conaxlearn8566 4 года назад

      @@cristina_machado Just wondering, were you running this in Windows environment?

  • @lukaivancupic7679
    @lukaivancupic7679 4 года назад +4

    Just leaving a quick note if somebody has problems with the "admingBeingEdited" returning null. In my URL I didn't have "?userId=" part for some reason so i didn't know how to get to the Id. This is the solution i found/came up with (hope it helps):
    string request = authContext.HttpContext.Request.Path.Value;
    string adminBeingEdited = request.Split('/')[3];
    Thank you a lot sir Venkat!

    • @marcol5374
      @marcol5374 4 года назад

      Why we cannot have the ?userId= syntax...
      I have the same issue...

    • @marcol5374
      @marcol5374 4 года назад

      I understand. You must use this policy to protect ManageRoles and ManageClaims action methods, not on EditUser...
      This is my error.

    • @muhammadwaqasiqbal8243
      @muhammadwaqasiqbal8243 4 года назад

      Is this for 2.2 or 3.1? im having this issue with 2.2!

    • @canasjoe1
      @canasjoe1 4 года назад +1

      This is because of the routing value
      app.UseMvc(routes => routes.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}"));
      im guessing you didnt call the passed in parameter 'userId' and you called it just 'id'.
      on the editUser view we create the button

      Manage Roles
      if you specify the asp-route attribute as asp-route-id the map route recognises this and keeps it part of the path.
      if the asp-route attribute is userId as the mapRoute cand find this structure so it makes it a querystring.
      for your code to work with querystring you can do what you say or change the expected parameter from id to userId as he did. and it will come up as a querystring. obviously if you chnage the ap-route attribute you will need to change the contorller action parameter too.

  • @anbumani6083
    @anbumani6083 6 месяцев назад

    Always the best.☝

  • @phanidivi3613
    @phanidivi3613 5 лет назад +1

    What an explanation venkat sir...really hat off once again.Thank you so much

  • @sakthir3892
    @sakthir3892 5 лет назад +1

    Good morning sir, Nice Explanation..

  • @loveunimeanit
    @loveunimeanit 5 лет назад +1

    Thanks for educating us ... can you make a video on external provider authentication in ASP.NET Core ... thanks

    • @Csharp-video-tutorialsBlogspot
      @Csharp-video-tutorialsBlogspot  5 лет назад +1

      For sure, we will cover external authentication providers like Google, Facebook, Microsoft, Twitter etc in our upcoming videos. Please stay tuned. Thank you very much for your valuable suggestion.

  • @sairk6174
    @sairk6174 5 лет назад

    THANKS A LOT VENKAT GARU..

  • @nisargshah5485
    @nisargshah5485 4 года назад

    Hello,
    I have a question regarding anti forgery token,,,,how can i change anti forgery token's value before and after login.and how can i manage that token's value which should be unique at every new request.
    Thanks in advance

  • @sumankarmitra5819
    @sumankarmitra5819 3 года назад

    If we are using Custom Filter at controller level, then how to bypass/allowanonymous for a certain action under this controller?

  • @vaseemahmad2363
    @vaseemahmad2363 5 лет назад

    Sir, I want to ask you something,My question is how much I should to learn sql server for any Programming language?

    • @technicalcrackedinterviews4392
      @technicalcrackedinterviews4392 5 лет назад

      Hi Vaseem, SQL SERVER is very easy technology and you can cover it with in maximum 1 month only. And Kudvenkat sir have already posted very nice videos for the same you can visit there.

    • @vaseemahmad2363
      @vaseemahmad2363 5 лет назад +1

      @@technicalcrackedinterviews4392 Thanks a lot Sir

    • @LuigiZambetti
      @LuigiZambetti 5 лет назад +1

      @@technicalcrackedinterviews4392 In 1 month only you can get a bare basic knowledge of T-SQL. SQL Server itself deserve a bit more time.

    • @technicalcrackedinterviews4392
      @technicalcrackedinterviews4392 5 лет назад

      Luigi Zambetti Yes you are right but first basic knowledge is mandatory. Full knowledge always comes with your experience.

  • @hossammetwally07
    @hossammetwally07 5 лет назад

    Please, why did you delete the policy from EditRole action I did not get it

  • @imtiajahammad3586
    @imtiajahammad3586 3 года назад

    string adminIdBeingEdited = authFilterContext.HttpContext.Request.Query["userId"];
    returns userId with an extra space.
    I am using core 2.1.1 version.
    can anyone tell me why?

  • @zorigdavaag.8354
    @zorigdavaag.8354 4 года назад +2

    authFilterContext is always null please Help

    • @zorigdavaag.8354
      @zorigdavaag.8354 4 года назад

      i Found a Solution:
      string LoggedInAdminId = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value.ToString();
      if (LoggedInAdminId==null)
      {
      return Task.CompletedTask;
      }
      string adminIdBeingEdited = contextAccessor.HttpContext.Request.Query["userId"];
      if (adminIdBeingEdited==null)
      {
      return Task.CompletedTask;
      }
      if (context.User.IsInRole("Admin") &&
      context.User.HasClaim(claim =>
      claim.Type == "Edit Role" && claim.Value == "true") && adminIdBeingEdited.ToLower() != LoggedInAdminId.ToLower())
      {
      context.Succeed(requirement);
      }
      return Task.CompletedTask;

    • @zorigdavaag.8354
      @zorigdavaag.8354 4 года назад

      public CanEditOnlyOtherAdminRolesAndClaimsHandler(IHttpContextAccessor contextAccessor)
      {
      this.contextAccessor = contextAccessor?? throw new ArgumentNullException(/*nameof(httpContextAccessor)*/);
      }

    • @zorigdavaag.8354
      @zorigdavaag.8354 4 года назад

      services.AddHttpContextAccessor();

    • @rizwanaslam2071
      @rizwanaslam2071 4 года назад +1

      @@zorigdavaag.8354 Please explain /*nameof(httpContextAccessor)*/

    • @yaakov4041
      @yaakov4041 3 года назад

      I put here a belated answer which can give help for new visitors.
      This question was raised in 'stackoverflow' by a student of this kudvenkat's course and he quoted there that very code. I tried the answer number 2 there and it solved the error. Here is the address of the page : stackoverflow.com/questions/59197631/context-resource-as-authorizationfiltercontext-returning-null-in-asp-net-core
      The answer of "user12838074".
      We should replace the class "CanEditOnlyOtherAdminRolesAndClaimsHandler" by the class code that "user12838074" brings there.

  • @conaxlearn8566
    @conaxlearn8566 4 года назад

    I'm using .net core 3.1 and Venkat's code works fine for me.

    • @AkshayKumar-dz5ts
      @AkshayKumar-dz5ts 4 года назад

      it shouldnt work for .net core 3.1 cos context.resource returns null.

    • @conaxlearn8566
      @conaxlearn8566 4 года назад

      @@AkshayKumar-dz5ts So what do you think is the reason that in .net core 3.1 context .resource returns null?

    • @AkshayKumar-dz5ts
      @AkshayKumar-dz5ts 4 года назад

      @@conaxlearn8566
      no idea

    • @conaxlearn8566
      @conaxlearn8566 4 года назад

      @@AkshayKumar-dz5ts Exactly friend. So you shouldn't assume context.resource always returns null in 3.1, as it certainly returns what I needed for me, and I am using 3.1.

    • @AkshayKumar-dz5ts
      @AkshayKumar-dz5ts 4 года назад

      oh good for you but i meant if you followed his course as is then the chances are it wont but good for you my friend

  • @chhinsras
    @chhinsras 3 года назад

    i got context.user.claims = empty

  • @husam-ebish
    @husam-ebish 4 года назад

    If you working with .net core 3, take a look on this solution:
    stackoverflow.com/a/61560796/9334155

  • @theonewhonevergaveup785
    @theonewhonevergaveup785 5 лет назад

    very ez

  • @metalguy8117
    @metalguy8117 4 года назад

    RIP these tutorials. Many things you describe no longer work in ASP.NET Core 3.0 and above. Fuck this shit.