前言
HTTP Authentication 是很古老的东西. 已经很少地方会用到了. 但还是给我遇上了.
在做 Google Ads Offline Conversion 时, 它提供了 2 种方式让我 upload offline conversion.
第一种是顺风水的 best practice, 通过 Google Ads API. (OAuth + C# dll)
第二种是通过 Google Ads UI 设置一个 server task, 让它每天访问一个 HTTP 地址. 这个地址 provide 一个 .csv file, file 里面自然就是 offline conversion 需要的资料.
为了安全, 这个 HTTP request 就用上了 HTTP Authentication.
当然这个安全级别是蛮低的. but is ok, 毕竟 offline conversion 不会涉及太多敏感信息. 如果想更安全, 那就用 API 咯.
我只是纯粹想体验一下古老技术所以才玩玩的.
参考
Implementing Basic Authentication in ASP.NET Core Minimal API
Implementing Basic Authentication in ASP.NET 6
How to Add Basic Authentication to an ASP.NET Core Application: OAuth Security - Part 1
YouTube – Basic Authentication in DOT NET Core Web API using VS Code | .NET CORE 6.0 Tutorial
HTTP Authentication 介绍
有些资源需要被保护, 最简单的方法就是搞 username password. 所以 HTTP 就拟定了一个简单的 username password 潜规则, 让客户端和服务端用一个很简单的方式去实现简单的资源保护.
流程
它的流程是这样的.
1. 游览器请求一个被保护的资料
2. 服务端验证, 并返回 401 status 再加一个 header
4. 用户输入 username password 后, 游览器会再次发请求, 并且加上一个 header
header key: Authorization
header value: base64(username + ":" + password)
username password 会通过 base64 encode.
5. 服务器验证 username password 通过就 response 200
realm 是什么?
游览器支持记入多个 username password. 所以资源可以分组进行保护. 分组就是通过 realm 完成的
realm="a group name"
比如
/products (realm="product")
/models (realm="product")
/orders (realm="order")
当游览访问 products 后, 就会把 username password 记入起来, 并且记入它是 product group 的 username password
当访问 models 的时候, 游览器会直接附上 username password, 直接验证通过
当访问 orders 的时候, 游览器依然会直接附上 username password, 但这次显然是不能通过的, 因为资源组不同, username password 也不同嘛.
验证失败之后, 游览器获得 401 和 basic realm="order", 然后 popup > fill in username password > valid response > 最后把这个 username password 记入起来 under order group.
这时游览器就有了 2 pair username password, 一个负责 product group, 一个负责 order group 的资源访问.
ASP.NET Core Simple Test
dotnet new webapi -o TestHttpAuthentication
Controller
using System.Text; using Microsoft.AspNetCore.Mvc; namespace TestHttpAuthentication.Controllers; [ApiController] public class TestControllerController : ControllerBase { [HttpGet("products")] public ActionResult<List<string>> GetProducts() { // 游览器没有提供 username password header Authorization, 直接返回 401 if (!Request.Headers.Any(e => e.Key == "Authorization")) { Response.Headers.Add("WWW-Authenticate", "basic realm=\"product\""); return Unauthorized(); } // 从游览器的 header Authorization 拆解出 username password var base64 = Request.Headers.Authorization.ToString().Split(" ")[1]; var base64Bytes = Convert.FromBase64String(base64); var usernameAndPassword = Encoding.UTF8.GetString(base64Bytes); var username = usernameAndPassword.Split(":")[0]; var password = usernameAndPassword.Split(":")[1]; // 通过就返回 200 if (username == "keatkeat" && password == "password") { return new List<string> { "Product 1", "Product 2", "Product 3" }; } // 失败就返回 401 else { Response.Headers.Add("WWW-Authenticate", "basic realm=\"product\""); return Unauthorized(); } } }
效果
ASP.NET Core 封装 HTTP Authentication
ASP.NET Core 没有 build-in 的 Authentication 机制, 可能是因为很少人用又容易实现, 所以它就不做了. 那我们自己做一个呗.
参考
Implementing Basic Authentication in ASP.NET Core Minimal API
Working with custom authentication schemes in ASP.NET Core 6.0 Web API
Program.cs
namespace TestHttpAuthentication; public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddAuthentication() .AddScheme<BasicAuthenticationSchemeOptions, BasicAuthenticationHandler>("GoogleAdsBasicAuthentication", option => { option.SetRealm("Google Ads"); option.AddUser("keatkeat", "password"); }); builder.Services.AddAuthorization(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run(); } }
主要是添加了这几个
在 Identity – Without Identity Framework 有提过如何使用底层的 ASP.NET Core Authentication, 但那个依然是用了 build-in 的 CookieScheme.
而这里, 我们是创建了一个全新的 Scheme.
TestController.cs
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace TestHttpAuthentication.Controllers; [ApiController] public class TestControllerController : ControllerBase { [HttpGet("products")] [Authorize(AuthenticationSchemes = "GoogleAdsBasicAuthentication")] public ActionResult<List<string>> GetProducts() { return Ok(new List<string> { "Product 1", "Product 2", "Product 3" }); } [HttpGet("models")] public ActionResult<List<string>> GetModels() { return Ok(new List<string> { "Model 1", "Model 2", "Model 3" }); } }
BasicAuthentication.cs
using System.Security.Claims; using System.Text; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Options; namespace TestHttpAuthentication; public class BasicAuthenticationSchemeOptions : AuthenticationSchemeOptions { public string Realm { get; set; } = ""; public void SetRealm(string realm) { Realm = realm; } public List<User> Users = new(); public void AddUser(string username, string password) { Users.Add(new User { Username = username, Password = password, }); } public bool ValidUser(string username, string password) { return Users.Any(e => e.Username == username && e.Password == password); } public class User { public string Username { get; set; } = ""; public string Password { get; set; } = ""; } } public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationSchemeOptions> { public BasicAuthenticationHandler( IOptionsMonitor<BasicAuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock ) : base(options, logger, encoder, clock) { } protected override Task<AuthenticateResult> HandleAuthenticateAsync() { var authorization = Request.Headers.Authorization.ToString(); if (!authorization.StartsWith("Basic ")) return Fail(); var base64 = authorization.Split(" ")[1]; var base64Bytes = Convert.FromBase64String(base64); var usernameAndPassword = Encoding.UTF8.GetString(base64Bytes); var username = usernameAndPassword.Split(":")[0]; var password = usernameAndPassword.Split(":")[1]; if (Options.ValidUser(username, password)) { var claims = new List<Claim> { new Claim("name", username) }; // 不一定要放 name claims var identity = new ClaimsIdentity(claims, authenticationType: "Basic"); // 一定要 set authenticationType to Basic var claimsPrincipal = new ClaimsPrincipal(identity); return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, Scheme.Name))); } return Fail(); Task<AuthenticateResult> Fail() { Response.StatusCode = 401; Response.Headers.Add("WWW-Authenticate", $"basic realm=\"{Options.Realm}\""); return Task.FromResult(AuthenticateResult.Fail("Authentication failed")); } } }
蛮简单的, 一个 Options 配一个 Handler.
Handler 里面负责从 Request 获取信息, 然后验证通过与否.