Identity – HTTP Authentication
前言
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 获取信息, 然后验证通过与否.
Identity – HTTP Authentication的更多相关文章
- ASP.NET Core 身份认证 (Identity、Authentication)
Authentication和Authorization 每每说到身份验证.认证的时候,总不免说提及一下这2个词.他们的看起来非常的相似,但实际上他们是不一样的. Authentication想要说明 ...
- Asp.net core 学习笔记 ( Identity 之 Authentication )
和从前的 identity 区别不是很大. 从 2.1 开始 vs 模板的 identity 都被封装了起来, 你几乎看不到任何一行代码, 需要向下面这样打开它, 才能做修改. 说一下比较常用的配置 ...
- [SharePoint]SharePoint Claim base Authentication的一个比较好的介绍
User identity in AD DS is based on a user account. For successful authentication, the user provides ...
- 全新的membership框架Asp.net Identity(1)——.Net membership的历史
在Asp.net上,微软的membershop框架经历了Asp.net membership到Asp.net simple membership,再到现在的Asp.net Identity. 每一次改 ...
- MVC MemeberShip vs. Asp.net Identity
参考 从Membership 到 .NET4.5 之 ASP.NET Identity Extending Identity Accounts and Implementing Role-Based ...
- 框架Asp.net Identity
框架Asp.net Identity 在Asp.net上,微软的membershop框架经历了Asp.net membership到Asp.net simple membership,再到现在的Asp ...
- [转]The NTLM Authentication Protocol and Security Support Provider
本文转自:http://davenport.sourceforge.net/ntlm.html#ntlmHttpAuthentication The NTLM Authentication Proto ...
- 全新的membership框架Asp.net Identity
在Asp.net上,微软的membershop框架经历了Asp.net membership到Asp.net simple membership,再到现在的Asp.net Identity. 每一次改 ...
- MVC6 (ASP.NET5) 认证 (Asp.net identity) cookie模式 自定义认证
1.Startup类的Configure方法中, app.UseIdentity(); 改为 app.UseCookieAuthentication(options => { options.A ...
- OpenStack Identity API v3 extensions (CURRENT)
Table Of Contents Identity API v3 extensions (CURRENT) OS-ENDPOINT-POLICY API Associate policy and e ...
随机推荐
- 在缩小浏览器宽度的时候,图片会超出li的宽度
要确保在缩小浏览器宽度时,图片不会超出 <li> 元素的宽度,您可以为描述文本添加一些样式,以便让图片适应于 <li> 元素.一种常见的方法是使用 CSS 中的 max-wid ...
- oeasy教您玩转python - 003 - # - 继续运行
继续运行 回忆上次内容 在解释器里玩耍 print("Hello World") 1+1 编写了 py 文件 运行了 py 文件 这次我们继续丰富这个文件 分析 py 文件 我 ...
- OLOR:已开源,向预训练权值对齐的强正则化方法 | AAAI 2024
随着预训练视觉模型的兴起,目前流行的视觉微调方法是完全微调.由于微调只专注于拟合下游训练集,因此存在知识遗忘的问题.论文提出了基于权值回滚的微调方法OLOR(One step Learning, On ...
- 新版宝塔面板快速搭建WordPress新手教程
一.宝塔面板介绍 1. 介绍 宝塔面板是一款服务器管理软件,支持Windows和Linux系统,可以通过Web端轻松管理服务器,提升运维效率,该软件内置了创建管理网站.FTP.数据库.可视化文件管理器 ...
- Telegram手机号码反查工具
Telegram手机号码反查工具 项目地址:https://github.com/bellingcat/telegram-phone-number-checker v1.2.1版本 要求python的 ...
- RHCA cl210 016 流表 overlay
Overlay网络是建立在Underlay网络上的逻辑网络 underlay br-int 之间建立隧道 数据流量还是从eth1出去 只有vlan20 是geneve隧道.只有租户网络有子网,子网需要 ...
- 【Vue】13 VueRouter Part3 路由守卫
单页应用中,只存在一个HTML文件,网页的标签,是通过title标签显示的,我们在单页应用中如何修改? JS操作: window.document.title = "标签名称" 也 ...
- 阿里提供的免费pypi镜像服务器
介绍页地址: https://developer.aliyun.com/mirror/pypi 具体的镜像地址: https://mirrors.aliyun.com/pypi/
- 代码随想录Day7
454.四数相加Ⅱ 给你四个整数数组 nums1.nums2.nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足: 0 <= i, j, k ...
- 2.6倍!WhaleTunnel 客户POC实景对弈DataX
作为阿里早期的开源产品,DataX是一款非常优秀的数据集成工具,普遍被用于多个数据源之间的批量同步,包括类似Apache DolphinScheduler的Task类型也对DataX进行了适配和增强, ...