You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You Have To Tell In The Startup You Are going to use authentication write below code in start.cs and this says you are adding the authentication service in your application using a cookies
builder.Services.AddAuthorization(options =>{//Claim is required for this policy is UserId if any user have Claim Named UserId and Value 1,2,3,4,5 then this will work otherwise this will not give you the access options.AddPolicy("SuperUser",policy => policy.RequireClaim("UserId","1","2","3","4","5"));});
after that you have to tell the application to add authentication and authorization
app.UseAuthentication();
app.UseAuthorization();
And Then You Have to authenticate user like this
if(username=="admin"&&password=="dotnet"){//if i change the UserId to 6 it cann't access Privacy method Because we have registerd A Policy With a claim named UserId in Program/startup.csvaridentity=new ClaimsIdentity(new[]{new Claim("UserId","1")}, CookieAuthenticationDefaults.AuthenticationScheme);varprinciple=new ClaimsPrincipal(identity);varlogin= HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principle);return RedirectToAction("Index","Home");}
now you have to use Policy base authorization for a method or a controller so you can simply provide a parameter called Policy to the Authorize attribute Like this [Authorize(Policy = "SuperUser")]