Asp.net core uses DI to implement a Custom User System, instead of ControllerBase. User,

Source: Internet
Author: User

Asp.net core uses DI to implement a Custom User System, instead of ControllerBase. User,
Preface

In many cases, we do not need the complicated user system that comes with asp.net core. Based on roles and various concepts, we also need to use EF Core, in addition, information is stored in cookies for communication in web applications (I do not like to put in cookies, because when I run a web application on the safari browser in the mac system, cross-Domain cookie settings are not supported. You have to use a special method. Remember to use iframe, which is very troublesome. So I still like to include custom headers ), after using it, I felt that Microsoft had kidnapped me. However, this is completely personal preferences. You can simply follow your own preferences. Here I provide another way for you to choose from.

I am using asp.net core's dependency injection to define a set of user authentication and authorization for my own system. You can refer to this to define your own, not limited to the user system.

Aspect-oriented programming (AOP)

In my opinion, both Middleware and Filter are in asp.net core. We can put authentication and authorization in these two places. I personally prefer to put authentication in Middleware. I can intercept and return illegal attacks in advance.

Dependency injection (DI)

Dependency injection has three lifecycles.

1. Initiate and end the same request. (Services. AddScoped)

2. Each injection is created. (Services. AddTransient)

3. Singleton: The application starts and ends. (Services. AddSingleton)

My Custom User class uses services. AddScoped.

Procedure 1. Define a user class
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

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 the Custom User Class 6 services. addScoped (typeof (MyUser); 7... 8}

The Custom User class is registered through services. AddScoped, because I want it to reference the same object in the same request, Middleware, filter, and controller.

3. Inject to Middleware
1 // You may need to install the Microsoft. aspNetCore. http. export actions package into your project 2 public class AuthenticationMiddleware 3 {4 private readonly RequestDelegate _ next; 5 private IOptions <HeaderConfig> _ optionsAccessor; 6 7 public AuthenticationMiddleware (RequestDelegate next, IOptions <HeaderConfig> optionsAccessor) 8 {9 _ next = next; 10 _ optionsAccessor = optionsAccessor; 11} 12 13 p Ublic async Task Invoke (HttpContext httpContext, MyUser user) 14 {15 var token = httpContext. Request. Headers [_ optionsAccessor. Value. AuthHeader]. FirstOrDefault (); 16 if (! IsValidate (token) 17 {18 httpContext. response. statusCode = (int) HttpStatusCode. forbidden; 19 httpContext. response. contentType = "text/plain"; 20 await httpContext. response. writeAsync ("UnAuthentication"); 21} 22 else23 {24 // set the user's token25 user. token = token; 26 await _ next (httpContext); 27} 28} 29 30 // you can add some encryption and decryption to determine the validity, free to use 31 private bool IsValidate (string token) 32 {33 return! String. isNullOrEmpty (token); 34} 35} 36 37 // Extension method used to add the middleware to the HTTP request pipeline.38 public static class failed {40 public static IApplicationBuilder UseAuthenticationMiddleware (this IApplicationBuilder builder) 41 {42 return builder. useMiddleware <AuthenticationMiddleware> (); 43} 44}

I found that if you want to inject interfaces/classes into Middleware in Scoped mode, you need to put the classes/interfaces to be injectedInvokeFunctionParametersBut not in the Middleware constructor. I guess this is why Middleware does not inherit the base class or interface and defines Invoke in the base class or interface, if it defines Invoke in the base class or interface, it is bound that the Invoke parameter should be fixed to death, so it is not easy to inject dependencies.

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 app. addNLogWeb (); 9 10 // The Middleware1 authentication must be added in addition to the special path. 1 app. MapWhen (context =>! Context. Request. Path. StartsWithSegments ("/api/token") 12 &&! Context. request. path. startsWithSegments ("/swagger"), x => 13 {14 // use the custom Middleware15 x. useAuthenticationMiddleware (); 16 // use the general Middleware17 ConfigCommonMiddleware (x); 18}); 19 // use the general Middleware20 ConfigCommonMiddleware (app ); 21 22 // Enable middleware to serve generated Swagger as a JSON endpoint.23 app. useSwagger (); 24 25 // Enable middleware to serve swagger-ui (HTML, JS, CSS etc .), specifying the Swagger JSON endpoint.26 app. useSwaggerUI (c => 27 {28 c. swaggerEndpoint ("/swagger/v1/swagger. json "," My API V1 "); 29}); 30} 31 32 // configure the General Middleware33 private void ConfigCommonMiddleware (IApplicationBuilder app) 34 {35 // cors36 app. useCors ("AllowAll"); 37 38 app. useExceptionMiddleware (); 39 // app. useLogRequestMiddleware (); 40 app. useMvc (); 41}

For example, if you want to obtain a token, you do not need to authenticate the token to view the api documentation.

5. Inject to Filter
 1     public class NeedAuthAttribute : ActionFilterAttribute 2     { 3private string _name = string.Empty; 4private MyUser _user; 5  6         public NeedAuthAttribute(MyUser user, string name = "") 7         { 8             _name = name; 9             _user = user;10         }11 12         public override void OnActionExecuting(ActionExecutingContext context)13         {14             this._user.UserName = "aaa";15         }16     }

Here I create a class with string parameters, because this Filter may be reused, for example, limiting an interface to access only by some user, this string can store the user ID.

Filters can also inject database access classes, so that we can get the corresponding user information through token in the database.

6. Use Filter
1 [TypeFilter(typeof(NeedAuthAttribute), Arguments = new object[]{ "bbb" }, Order = 1)]2 public class ValuesController : Controller

TypeFilter is used here to load the Filter with dependency injection, and parameters can be set in the order of filters.

The default Filter Order is global settings-> Controller-> Action, and Order is 0 by default. 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         ...10     }

Injection to the Controller constructor, so that we can use our custom user in the Controller Action to know which user is calling this 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.