控制台应用程序使用HttpClient
向ASP核心应用程序发送基本身份验证请求。
HttpClient client = ...
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
encoding.GetBytes($"{user.UserName}:{user.Password}")));
var response = await client.SendAsync(request);
ASP Core应用的配置如下(为简化起见,内联路由):
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseRouting(options =>
{
options.MapPost("/login", async (httpContext) =>
{
// get user creds
var authHeader = httpContext.Request.Headers["Authorization"].First().Substring("Basic ".Length).Trim();
...
// create claim and identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
// sign user in
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
});
});
}
当客户端收到响应时,会有一个名为Set-Cookie
的标头,其值类似于".AspNetCore.Cookies=foooooobarrrrrr; path=/; secure; samesite=lax; httponly"