Role-based authorization in ASP. NET Core 2.1

Source: Internet
Author: User
Role-based authorization in ASP. NET Core 2.1

Authorization is the process of describing what a user can do. For example, only administrators can be allowed to install and uninstall software on their computers. Users who are not administrators can only use the software to install and uninstall software. It is independent and is used in conjunction with authentication and requires an authentication mechanism. For an application, you first need to authenticate and then authorize.

Yi Le Zhu
Original link: www.cnblogs.com/yilezhu/p/9508267.html

Identity is a membership system that allows us to add login functionality to our applications, which may belong to one or more roles. For example, "User1" belongs to the "Admin" role, "User2" is the role of "HR".
We can use the Authorizefilter feature on controllers in our MVC or Web API applications to control user access. Role-based authorization checks whether the logged-on user has permission to access the page. Here developers can add roles to their code.
Here we use an example to illustrate, we will create three characters, corresponding we will build three users. The code is as follows:

public void Configure (Iapplicationbuilder app, Ihostingenvironment env, IServiceProvider serviceprovider) {.... ..... app. USEMVC (routes = {routes.      MapRoute (name: "Default", Template: "{controller=home}/{action=index}/{id}");        }); Createroles (serviceprovider).  Wait (); } Private Async Task createroles (IServiceProvider serviceprovider) {//initializing custom roles var Rolema      Nager = serviceprovider.getrequiredservice<rolemanager<identityrole>> ();      var Usermanager = serviceprovider.getrequiredservice<usermanager<identityuser>> ();      String[] Rolenames = {"Admin", "User", "HR"};        Identityresult Roleresult;          foreach (Var roleName in rolenames) {var roleexist = await rolemanager.roleexistsasync (roleName); if (!roleexist) {//create the roles and seed them to the Database:question 1 roleres Ult = await RolemAnager.          Createasync (New Identityrole (RoleName));        }} Identityuser user = await Usermanager.findbyemailasync ("jignesh@gmail.com");              if (user = = null) {user = new Identityuser () {UserName = "jignesh@gmail.com",          Email = "jignesh@gmail.com",};      Await Usermanager.createasync (user, "test@123");          } await Usermanager.addtoroleasync (user, "Admin");        Identityuser user1 = await Usermanager.findbyemailasync ("tejas@gmail.com");              if (User1 = = null) {user1 = new Identityuser () {UserName = "tejas@gmail.com",          Email = "tejas@gmail.com",};      Await Usermanager.createasync (user1, "test@123");        } await Usermanager.addtoroleasync (user1, "User");        Identityuser user2 = await Usermanager.findbyemailasync ("rakesh@gmail.com");           if (user2 = = null) {user2 = new Identityuser () {   UserName = "Rakesh@gmail.com", Email = "rakesh@gmail.com",};      Await Usermanager.createasync (User2, "test@123");    } await Usermanager.addtoroleasync (User2, "HR");    }

We can use the roles property of the authorize property to specify the roles that have access to the requested resource. For example, the following code allows an action method that is assigned the user of the "Admin" role to access.

[Authorize(Roles = "Admin")]  public IActionResult OnlyAdminAccess()  {      ViewData["role"] = "Admin";      return View("MyPage");  

We can use the comma-separated list of characters in English to allow multiple roles to access the method. For example, in the following code snippet, the action method can only be accessed by users of the "Admin" or "user" role.

[Authorize(Roles = "Admin,User")]  public IActionResult MultipleAccess()  {      ViewData["role"] = "Admin";      return View("MyPage");  

We can also use the following code for multi-role access control

[Authorize(Roles = "Admin")]  [Authorize(Roles = "User")]  public IActionResult MultipleAccess()  {      ViewData["role"] = "Admin";      return View("MyPage");  
Policy-based role checking

We can also create policy-based access control. We can use the authorization service to add and register policies. In the following code, we create a policy that allows only users with the "Admin" role to access.

public void ConfigureServices(IServiceCollection services)  {  ....  ....  services.AddAuthorization(options =>     {         options.AddPolicy("OnlyAdminAccess", policy => policy.RequireRole("Admin"));     });  

We can use the "policy" attribute of the authorize attribute to apply policies

[Authorize(Policy = "OnlyAdminAccess")]  public IActionResult PolicyExample()  {      ViewData["role"] = "Admin";      return View("MyPage");  

Using this strategy we can also apply role-based authorization in the Razor page. For example, if we have a "test1.cshtml" Razor page, and this page only allows users with the "Admin" role to access, we can use the following code to perform authorization access control on the Razor page.

public void ConfigureServices(IServiceCollection services)  {      ...      ...      services.AddMvc().AddRazorPagesOptions(options =>      {          options.Conventions.AuthorizePage("/test1", "OnlyAdminAccess");          }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);        services.AddAuthorization(options =>      {          options.AddPolicy("OnlyAdminAccess", policy => policy.RequireRole("Admin"));      });  }  
Summarize

This article is a translation of the www.c-sharpcorner.com/article/role-base-authorization-in-asp-net-core-2-1/article, which describes the ASP. 2.1 Role-based authorization, the content is very simple, easy to understand!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.