.net identity usage

From Logic Wiki
Jump to: navigation, search


Create a role

RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MyDbContext()));
var str = RoleManager.Create(new IdentityRole(roleName));

Add user to a role

var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

Checking a role

[Authorize(Roles = "Admin, User")]

Bearer

app.UseJwtBearerAuthentication(new JwtBearerOptions  
{
   AutomaticAuthenticate = true,
   AutomaticChallenge = true,
   TokenValidationParameters = new TokenValidationParameters
   {
       ValidateIssuer = true,
       ValidIssuer = "https://issuer.example.com",

       ValidateAudience = true,
       ValidAudience = "https://yourapplication.example.com",

       ValidateLifetime = true,
   }
});

Bearer token scheme policy selection in attribute

[Authorize(ActiveAuthenticationSchemes = "Bearer")]

Policy

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();

   services.AddAuthorization(options =>
   {
       options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
   });
}

Claim

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();

   services.AddAuthorization(options =>
   {
       options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("EmployeeNumber"));
   });
}
[Authorize(Policy = "EmployeeOnly")]
public IActionResult VacationBalance()
{
   return View();
}

Custom Policy-Based Authorization

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();

   services.AddAuthorization(options =>
   {
       options.AddPolicy("Over21",
                         policy => policy.Requirements.Add(new MinimumAgeRequirement(21)));
   });
}
[Authorize(Policy="Over21")]
public class AlcoholPurchaseRequirementsController : Controller
{...

Requirements

public class MinimumAgeRequirement : IAuthorizationRequirement
{
   public MinimumAgeRequirement(int age)
   {
       MinimumAge = age;
   }

   protected int MinimumAge { get; set; }
}

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies

View Based Authorization

@if (await AuthorizationService.AuthorizeAsync(User, "PolicyName"))
  {

This paragraph is displayed because you fulfilled PolicyName.

  }