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

ASP.NET Core 实现基本认证的示例代码

所以在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);
   }
}
// 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认证的服务端已经完成,现在可以在浏览器测试:

ASP.NET Core 实现基本认证的示例代码

进一步思考?

浏览器在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认证是随处可见的基础认证协议,本文期待以最清晰的方式帮助你理解协议:

实现了基本认证协议服务端,客户端;

标签:
ASP.NET,Core,认证

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“ASP.NET Core 实现基本认证的示例代码”

暂无“ASP.NET Core 实现基本认证的示例代码”评论...

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。