asp.net core利用DI实现自定义用户系统,脱离ControllerBase.User
前言
很多時(shí)候其實(shí)我們并不需要asp.net core自帶的那么復(fù)雜的用戶系統(tǒng),基于角色,各種概念,還得用EF Core,而且在web應(yīng)用中都是把信息存儲(chǔ)到cookie中進(jìn)行通訊(我不喜歡放cookie中,因?yàn)橛写挝以趍ac系統(tǒng)中的safari瀏覽器運(yùn)行web應(yīng)用時(shí),碰到跨域cookie設(shè)不上,非要使用個(gè)很特殊的方法,記得是iframe,挺麻煩的,所以我還是喜歡放自定義header中), 用了以后感覺被微軟給綁架了。不過這完全是個(gè)人喜好,大家完全可以按自己喜歡的來,我這里提供了另外一條路,大家可以多一種選擇。
我這邊是利用asp.net core的依賴注入,定義了一套屬于自己系統(tǒng)的用戶認(rèn)證與授權(quán),大家可以參考我這個(gè)來定義自己的,也不局限于用戶系統(tǒng)。
面向切面編程(AOP)
在我看來,Middleware與Filter都是asp.net core中的切面,我們可以把認(rèn)證與授權(quán)放到這兩塊地方。我個(gè)人比較喜歡把認(rèn)證放到Middleware,可以提早把那些不合法的攻擊攔截返回。
依賴注入(DI)
依賴注入有3種生命周期
1. 在同一個(gè)請(qǐng)求發(fā)起到結(jié)束。(services.AddScoped)
2. 每次注入的時(shí)候都是新建。(services.AddTransient)
3. 單例,應(yīng)用開始到應(yīng)用結(jié)束。(services.AddSingleton)
我的自定義用戶類采用的是services.AddScoped。
具體做法
1. 定義用戶類
1 // 用戶類,隨便寫的 2 public class MyUser 3 { 4 public string Token { get; set; } 5 public string UserName { get; set; } 6 }2. 注冊(cè)用戶類
Startup.cs中的ConfigureServices函數(shù):
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 // 注冊(cè)自定義用戶類 6 services.AddScoped(typeof(MyUser)); 7 ... 8 }自定義用戶類,是通過services.AddScoped方式進(jìn)行注冊(cè)的,因?yàn)槲蚁M谕粋€(gè)請(qǐng)求中,Middleware, filter, controller引用到的是同一個(gè)對(duì)象。
3. 注入到Middleware
1 // You may need to install the Microsoft.AspNetCore.Http.Abstractions 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 public 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 else 23 { 24 // 設(shè)置用戶的token 25 user.Token = token; 26 await _next(httpContext); 27 } 28 } 29 30 // 隨便寫的,大家可以加入些加密,解密的來判斷合法性,大家自由發(fā)揮 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 AuthenticationMiddlewareExtensions 39 { 40 public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder builder) 41 { 42 return builder.UseMiddleware<AuthenticationMiddleware>(); 43 } 44 }我發(fā)現(xiàn)如果要把接口/類以Scoped方式注入到Middleware中,就需要把要注入的類/接口放到Invoke函數(shù)的參數(shù)中,而不是Middleware的構(gòu)造函數(shù)中,我猜這也是為什么Middleware沒有繼承基類或者接口,在基類或者接口中定義好Invoke的原因,如果它在基類或者接口中定義好Invoke,勢(shì)必這個(gè)Invoke的參數(shù)要固定死,就不好依賴注入了。
4. 配置某些路徑才會(huì)使用該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 // 除了特殊路徑外,都需要加上認(rèn)證的Middleware 11 app.MapWhen(context => !context.Request.Path.StartsWithSegments("/api/token") 12 && !context.Request.Path.StartsWithSegments("/swagger"), x => 13 { 14 // 使用自定義的Middleware 15 x.UseAuthenticationMiddleware(); 16 // 使用通用的Middleware 17 ConfigCommonMiddleware(x); 18 }); 19 // 使用通用的Middleware 20 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 // 配置通用的Middleware 33 private void ConfigCommonMiddleware(IApplicationBuilder app) 34 { 35 // cors 36 app.UseCors("AllowAll"); 37 38 app.UseExceptionMiddleware(); 39 // app.UseLogRequestMiddleware(); 40 app.UseMvc(); 41 }像獲取token啊,查看api文檔啊就不需要認(rèn)證了。
5. 注入到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 12 public override void OnActionExecuting(ActionExecutingContext context) 13 { 14 this._user.UserName = "aaa"; 15 } 16 }這里我創(chuàng)建的是個(gè)帶字符串參數(shù)的類,因?yàn)榭紤]到這個(gè)Filter有可能會(huì)被復(fù)用,比如限制某個(gè)接口只能被某種用戶訪問, 這個(gè)字符串便可以存某種用戶的標(biāo)識(shí)。
Filter中還可以注入數(shù)據(jù)庫(kù)訪問的類,這樣我們便可以到數(shù)據(jù)庫(kù)中通過token來獲取到相應(yīng)的用戶信息。
6. 使用Filter
1 [TypeFilter(typeof(NeedAuthAttribute), Arguments = new object[]{ "bbb" }, Order = 1)] 2 public class ValuesController : Controller這里使用了TypeFilter,以加載使用了依賴注入的Filter, 并可以設(shè)置參數(shù),跟Filter的順序。
默認(rèn)Filter的順序是 全局設(shè)置->Controller->Action, Order默認(rèn)都為0,我們可以通過設(shè)置Order來改變這個(gè)順序。
7. 注入到Controller
1 public class ValuesController : Controller 2 { 3 private MyUser _user; 4 5 public ValuesController(MyUser user) 6 { 7 _user = user; 8 } 9 ... 10 }注入到Controller的構(gòu)造函數(shù)中,這樣我們就可以在Controller的Action中使用我們自定義的用戶,就能知道到底當(dāng)前是哪個(gè)用戶在調(diào)用這個(gè)Action。
?
轉(zhuǎn)載于:https://www.cnblogs.com/nickppa/p/6903694.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的asp.net core利用DI实现自定义用户系统,脱离ControllerBase.User的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 足球起源
- 下一篇: 打开mobilenet——ssd的dem