ASP. NET core uses Di for custom user systems

Source: Internet
Author: User

Objective

Most of the time, we don't need the complex user system that comes with ASP. The role-based, the concepts, the EF core, and the Web app that stores the information in a cookie for communication (I don't like cookies, Because once I ran the web app on my Mac system Safari browser, I encountered a cross-domain cookie is not set up, do not want to use a very special method, remember is an IFRAME, very troublesome, so I still like to put in a custom header), with the feeling was later kidnapped by Microsoft. But this is completely a person's preference, we can completely according to their favorite, I provide another way, we can choose one more.

My side is the use of ASP. NET core Dependency injection, define a set of their own system of user authentication and authorization, you can refer to my this to define their own, not limited to the user system.

Facet-oriented programming (AOP)

In my opinion, both middleware and filter are facets in ASP. We can put authentication and authorization in both places. I personally prefer to put the certification into the middleware, can be early to the illegal attacks to intercept the return.

Dependency Injection (DI)

There are 3 life cycles of dependency injection

1. Initiation to the end of the same request. (Services. addscoped)

2. Each time the injection is new. (Services. AddTransient)

3. Single case, application start to end of application. (Services. Addsingleton)

My custom user class uses services. addscoped.

Specific practices

1. Defining User Classes


1     //user class, casually written 2 public     class MyUser3     {4 public         string Token {get; set;} 5 public         string UserName {get; set;} 6     }

2. Registered User Class

The Configureservices function in Startup.cs:


1         //This method gets called by the runtime. Use this method to add services to the CONTAINER.2 public         void Configureservices (iservicecollection services) 3         {4             ... 5             //Register custom user Class 6             services. Addscoped (typeof (MyUser)); 7 ...             8         }

Custom user classes are through services. Addscoped Way to register because I want it in the same request, middleware, filter, the controller refers to the same object.

3. Inject into the middleware


 1//need to install the Microsoft.AspNetCore.Http.Abstractions-your project 2 public class Authenticationmiddleware 3 {4 private readonly requestdelegate _next; 5 Private Ioptions

I found that if I were to inject the interface/class into the middleware in scoped, I would need to put the class/interface to inject into the parameters of the Invoke function instead of the middleware constructor. I guess this is also why middleware does not inherit the base class or interface, the reason why invoke is defined in the base class or interface, if it is defined in the base class or interface invoke, it is bound to this invoke parameter to fixed dead, it is not good to rely on injection.

4. Configure some paths to use the middleware


 1//This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         2 public void Configure (Iapplicationbuilder app, Ihostingenvironment env, Iloggerfactory loggerfactory) 3             {4 Loggerfactory.addconsole (configuration.getsection ("Logging")); 5 Loggerfactory.adddebug (); 6 Set up Nlog 7 loggerfactory.addnlog (); 8 apps. Addnlogweb (); 9 10//In addition to the special path, you need to add a certified Middleware11 app. Mapwhen (context =!context. Request.Path.StartsWithSegments ("/api/token") &&!context.                 Request.Path.StartsWithSegments ("/swagger"), x =>13 {14//using a custom MIDDLEWARE15             X.useauthenticationmiddleware (); 16//Using a universal Middleware17 configcommonmiddleware (x); 18 }); 19//Use common MIDDLEWARE20 configcommonmiddleware (app); 21 22//Enable middleware to serve generated Swagger as a JSON endpoint.23 app. Useswagger (): +/Enable middleware to serve Swagger-ui (HTML, JS, CSS etc), specifying the swagger JSON endpoint.26 app.             Useswaggerui (c =>27 {c.swaggerendpoint ("/swagger/v1/swagger.json", "My API V1"); 29 }); 30}31 32//configuration Common Middleware33 private void Configcommonmiddleware (Iapplicationbuilder a PP) {+//cors36 app. Usecors ("Allowall"), the PNs app. Useexceptionmiddleware ();//App. Uselogrequestmiddleware (), app. Usemvc (); 41}

Like getting tokens, look at the API documentation and don't need authentication.

5. Inject into the filter


1 Public     class Needauthattribute:actionfilterattribute 2     {3         private string _name = String. Empty; 4         private MyUser _user; 5  6 Public         needauthattribute (MyUser user, string name = "") 7         {8             _name = Name ; 9             _user = user;10         }11 public         override void OnActionExecuting (ActionExecutingContext context)             This._user. UserName = "AAA";         }16     }

Here I create a class with a string parameter, because the filter may be reused, such as restricting an interface to be accessible only by some user, and this string can be used to store some kind of user's identity.

Filter can also inject the database access class, so that we can go to the database through token to obtain the corresponding user information.

6. Use the filter


1 [TypeFilter (typeof (Needauthattribute), Arguments = new object[]{"BBB"}, Order = 1)]2 public class Valuescontroller:c Ontroller

The TypeFilter is used here to load the filter using the dependency injection, and the parameters can be set in the order of the filter.

The order of the default filter is the global setting->controller->action, order defaults to 0, and we can change this order by setting order.

7. Inject to Controller


1 Public     class Valuescontroller:controller 2     {3         private MyUser _user; 4  5 public         Valuescontroller (MyUser user) 6         {7             _user = user; 8         } 9         ... Ten     }

Injected into the controller's constructor so that we can use our custom user in the Controller's action to know exactly which user is currently invoking the action.

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.