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();
@@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
@@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; } } }
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!
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.
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.
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
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?
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.
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.
@@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.
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();
Cheers good sir
Hello! Can you explain better where did you put the code? I tried but it did not work for me. Thank you.
@@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
@@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;
}
}
}
@@cristina_machado Just wondering, were you running this in Windows environment?
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!
Why we cannot have the ?userId= syntax...
I have the same issue...
I understand. You must use this policy to protect ManageRoles and ManageClaims action methods, not on EditUser...
This is my error.
Is this for 2.2 or 3.1? im having this issue with 2.2!
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.
Always the best.☝
Good morning sir, Nice Explanation..
What an explanation venkat sir...really hat off once again.Thank you so much
Right phani he is genius personality forever.
THANKS A LOT VENKAT GARU..
Thanks for educating us ... can you make a video on external provider authentication in ASP.NET Core ... thanks
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.
If we are using Custom Filter at controller level, then how to bypass/allowanonymous for a certain action under this controller?
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
Please, why did you delete the policy from EditRole action I did not get it
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?
Sir, I want to ask you something,My question is how much I should to learn sql server for any Programming language?
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.
@@technicalcrackedinterviews4392 Thanks a lot Sir
@@technicalcrackedinterviews4392 In 1 month only you can get a bare basic knowledge of T-SQL. SQL Server itself deserve a bit more time.
Luigi Zambetti Yes you are right but first basic knowledge is mandatory. Full knowledge always comes with your experience.
authFilterContext is always null please Help
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;
public CanEditOnlyOtherAdminRolesAndClaimsHandler(IHttpContextAccessor contextAccessor)
{
this.contextAccessor = contextAccessor?? throw new ArgumentNullException(/*nameof(httpContextAccessor)*/);
}
services.AddHttpContextAccessor();
@@zorigdavaag.8354 Please explain /*nameof(httpContextAccessor)*/
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.
If you working with .net core 3, take a look on this solution:
stackoverflow.com/a/61560796/9334155
I'm using .net core 3.1 and Venkat's code works fine for me.
it shouldnt work for .net core 3.1 cos context.resource returns null.
@@AkshayKumar-dz5ts So what do you think is the reason that in .net core 3.1 context .resource returns null?
@@conaxlearn8566
no idea
@@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.
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
i got context.user.claims = empty
very ez
RIP these tutorials. Many things you describe no longer work in ASP.NET Core 3.0 and above. Fuck this shit.