asp.net core AuthenticationMiddleware 在WebApi中的的使用
在.net framework 4.5架構下使用認證(Authentication)授權(Authorization)。
IIS使用HttpModule進行認證(Authentication),我們可以選擇自己實現認證方式并在web.config中配置,當然也可以選擇IIS默認提供的幾種實現,這里不再繼續展開討論。?
asp.net core默認提供了幾種默認的實現方式,包括Identity,Facebook, Google, Microsoft Account, Twitter 等等。這里介紹Basic Authentication認證方式。asp.net core的請求通道由一系列的請求委托組成,一個一個順序執行。
實現Basic Authentication最簡單的方式是添加一個中間件。新建文件BasicAuthenticationMiddlerware
public sealed class BasicAuthenticationMiddlerware
? ? {
? ? ? ? private readonly RequestDelegate _next;
? ? ? ? public BasicAuthenticationMiddlerware(RequestDelegate next)
? ? ? ? {
? ? ? ? ? ? _next = next;
? ? ? ? }
? ? ? ? public async Task InvokeAsync(HttpContext context)
? ? ? ? {
? ? ? ? ? ? string authentication = context.Request.Headers["Authorization"];
? ? ? ? ? ? if (authentication != null && authentication.Contains("Basic"))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //Extract credentials
? ? ? ? ? ? ? ? var usernamePasswordStr = authentication.Trim().Split(" ")[1];
? ? ? ? ? ? ? ? var userNamAndPasswordArr = usernamePasswordStr.Split(':');
? ? ? ? ? ? ? ? if (userNamAndPasswordArr.Length != 2)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? context.Response.StatusCode = 401;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? var username = userNamAndPasswordArr[0];
? ? ? ? ? ? ? ? var password = userNamAndPasswordArr[1];
? ? ? ? ? ? ? ? /*
? ? ? ? ? ? ? ? ?* 根據用戶賬號密碼驗證用戶有效性
? ? ? ? ? ? ? ? ?* 如果有效
? ? ? ? ? ? ? ? ?* 執行 await _next.Invoke(context);
? ? ? ? ? ? ? ? ?* 否則
? ? ? ? ? ? ? ? ?* context.Response.StatusCode = 401;
? ? ? ? ? ? ? ? ?*/
? ? ? ? ? ? ? ? if (true)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? await _next.Invoke(context);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? context.Response.StatusCode = 401;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? context.Response.StatusCode = 401;?
? ? ? ? ? ? }
? ? ? ? ? ??
? ? ? ? }
? ? }
完成中間件的定義以后,在Startup.cs文件的Configure方法中注冊中間件以開啟驗證。注意,這里一定要添加在app.UseMvc()之前。
app.UseMiddleware<BasicAuthenticationMiddlerware>();?
或者通過添加IApplicationBuilder的擴張方法,再用擴展方法進行注冊。代碼如下
public static class BasicAuthenticationMiddlerwareExtension
? ? {
? ? ? ? public static IApplicationBuilder UseBasicAuthenticationMiddlerware(
? ? ? ? ? ? this IApplicationBuilder builder)
? ? ? ? {
? ? ? ? ? ? return builder.UseMiddleware<BasicAuthenticationMiddlerware>();
? ? ? ? }
? ? }
Startup.cs的Configure的內容如下
public void Configure(IApplicationBuilder app, IHostingEnvironment env)?
{
? ? ?if (env.IsDevelopment())
? ? ?{
? ? ? ? app.UseDeveloperExceptionPage();
? ? ?}
? ? ? ?app.UseBasicAuthenticationMiddlerware();
? ? ? ?app.UseMvc();
}
啟動WebApi。不添加頭文件Authorization,如預期返回401狀態碼。
?
添加頭部信息,如預期返回數據。
?
原文地址:http://www.cnblogs.com/Zhang-Xiang/p/7536803.html
.NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注
總結
以上是生活随笔為你收集整理的asp.net core AuthenticationMiddleware 在WebApi中的的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Configuration Extens
- 下一篇: WebSocket In ASP.NET