ASP.NET Core 實現基本認證


HTTP基本認證

       在HTTP中,HTTP基本認證(Basic Authentication)是一種允許網頁瀏覽器或其他客戶端程序以(用戶名:口令) 請求資源的身份驗證方式,不要求cookie,session identifier、login page等標記或載體。  

   -  所有瀏覽器據支持HTTP基本認證方式

   -  基本身證原理不保證傳輸憑證的安全性,僅被based64編碼,並沒有encrypted或者hashed,一般部署在客戶端和服務端互信的網絡,在公網中應用BA認證通常與https結合

 https://en.wikipedia.org/wiki/Basic_access_authentication

BA標准協議

BA認證協議的實施主要依靠約定的請求頭/響應頭, 典型的瀏覽器和服務器的BA認證流程:

① 瀏覽器請求應用了BA協議的網站,服務端響應一個401認證失敗響應碼,並寫入WWW-Authenticate響應頭,指示服務端支持BA協議

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="our site" # WWW-Authenticate響應頭包含一個realm域屬性,指明HTTP基本認證的是這個資源集

或客戶端在第一次請求時發送正確Authorization標頭,從而避免被質詢

②  客戶端based64(用戶名:口令),作為Authorization標頭值 重新發送請求。

Authorization: Basic userid:password

 

 所以在HTTP基本認證中認證范圍與 realm有關(具體由服務端定義)

 >  一般瀏覽器客戶端對於www-Authenticate質詢結果,會彈出口令輸入窗.

BA編程實踐

     aspnetcore網站利用FileServerMiddleware 將路徑映射到某文件資源, 現對該 文件資源訪問路徑應用 Http BA協議。

ASP.NET Core服務端實現BA認證:

     ①  實現服務端基本認證的認證過程、質詢邏輯

     ②  實現基本身份認證交互中間件BasicAuthenticationMiddleware ,要求對HttpContext使用 BA.Scheme

     ③  ASP.NET Core 添加認證計划 , 為文件資源訪問路徑啟用 BA中間件,注意使用UseWhen插入中間件

using System;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace EqidManager.Services
{
    public static class BasicAuthenticationScheme
    {
        public const string DefaultScheme = "Basic";
    }

    public class BasicAuthenticationOption:AuthenticationSchemeOptions
    {
        public string Realm { get; set; }
        public string UserName { get; set; }
        public string UserPwd { get; set; }
    }

    public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOption>
    {
        private readonly BasicAuthenticationOption authOptions;
        public BasicAuthenticationHandler(
            IOptionsMonitor<BasicAuthenticationOption> options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock)
            : base(options, logger, encoder, clock)
        {
            authOptions = options.CurrentValue;
        }

        /// <summary>
        /// 認證
        /// </summary>
        /// <returns></returns>
        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
                return AuthenticateResult.Fail("Missing Authorization Header");
            string username, password;
            try
            {
                var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':');
                 username = credentials[0];
                 password = credentials[1];
                 var isValidUser= IsAuthorized(username,password);
                if(isValidUser== false)
                {
                    return AuthenticateResult.Fail("Invalid username or password");
                }
            }
            catch
            {
                return AuthenticateResult.Fail("Invalid Authorization Header");
            }

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier,username),
                new Claim(ClaimTypes.Name,username),
            };
            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);
            return await Task.FromResult(AuthenticateResult.Success(ticket));
        }

        /// <summary>
        /// 質詢
        /// </summary>
        /// <param name="properties"></param>
        /// <returns></returns>
        protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.Headers["WWW-Authenticate"] = $"Basic realm=\"{Options.Realm}\"";
            await base.HandleChallengeAsync(properties);
        }

        /// <summary>
        /// 認證失敗
        /// </summary>
        /// <param name="properties"></param>
        /// <returns></returns>
        protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
        {
           await base.HandleForbiddenAsync(properties); 
        }

        private bool IsAuthorized(string username, string password)
        {
            return username.Equals(authOptions.UserName, StringComparison.InvariantCultureIgnoreCase)
                   && password.Equals(authOptions.UserPwd);
        }
    }
}
// HTTP基本認證Middleware
public static class BasicAuthentication { public static void UseBasicAuthentication(this IApplicationBuilder app) { app.UseMiddleware<BasicAuthenticationMiddleware>(); } } public class BasicAuthenticationMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public BasicAuthenticationMiddleware(RequestDelegate next, ILoggerFactory LoggerFactory) { _next = next;
_logger
= LoggerFactory.CreateLogger<BasicAuthenticationMiddleware>(); } public async Task Invoke(HttpContext httpContext, IAuthenticationService authenticationService) { var authenticated = await authenticationService.AuthenticateAsync(httpContext, BasicAuthenticationScheme.DefaultScheme); _logger.LogInformation("Access Status:" + authenticated.Succeeded); if (!authenticated.Succeeded) { await authenticationService.ChallengeAsync(httpContext, BasicAuthenticationScheme.DefaultScheme, new AuthenticationProperties { }); return; } await _next(httpContext); } }

 Startup.cs 文件添加並啟用HTTP基本認證

services.AddAuthentication(BasicAuthenticationScheme.DefaultScheme)
                .AddScheme<BasicAuthenticationOption, BasicAuthenticationHandler>(BasicAuthenticationScheme.DefaultScheme,null);
app.UseWhen(
            predicate:x => x.Request.Path.StartsWithSegments(new PathString(_protectedResourceOption.Path)),
            configuration:appBuilder => { appBuilder.UseBasicAuthentication(); }
    ); 

以上BA認證的服務端已經完成,現在可以在瀏覽器測試:

 

進一步思考?

瀏覽器在BA協議中行為: 編程實現BA客戶端,要的同學可以直接拿去

    /// <summary>
    /// BA認證請求Handler
    /// </summary>
    public class BasicAuthenticationClientHandler : HttpClientHandler
    {
        public static string BAHeaderNames = "authorization";
        private RemoteBasicAuth _remoteAccount;

        public BasicAuthenticationClientHandler(RemoteBasicAuth remoteAccount)
        {
            _remoteAccount = remoteAccount;
            AllowAutoRedirect = false;
            UseCookies = true;
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var authorization = $"{_remoteAccount.UserName}:{_remoteAccount.Password}";
            var authorizationBased64 = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
            request.Headers.Remove(BAHeaderNames);
            request.Headers.Add(BAHeaderNames, authorizationBased64);
            return base.SendAsync(request, cancellationToken);
        }
    }


  // 生成basic Authentication請求
            services.AddHttpClient("eqid-ba-request", x =>
                   x.BaseAddress = new Uri(_proxyOption.Scheme +"://"+ _proxyOption.Host+":"+_proxyOption.Port ) )
               .ConfigurePrimaryHttpMessageHandler(y => new BasicAuthenticationClientHandler(_remoteAccount){} )
               .SetHandlerLifetime(TimeSpan.FromMinutes(2));
仿BA認證協議中的瀏覽器行為

That's All .  BA認證是隨處可見的基礎認證協議,本文期待以最清晰的方式幫助你理解協議:

 實現了基本認證協議服務端,客戶端;

作者: JulianHuang
感謝您的認真閱讀,如有問題請大膽斧正;覺得有用,請下方 或加關注。本文歡迎轉載,但請保留此段聲明,且在文章頁面明顯位置注明本文的 作者及原文鏈接。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM