如何维护/证明HttpClient和ASP核心之间启用cookie的请求的身份验证?

时间:2019-05-21 01:00:36

标签: c# asp.net asp.net-core

控制台应用程序使用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"

  • 我现在应该在客户端上执行什么操作,以确保将来(来自此客户端)的请求被身份验证为该特定用户?
  • 在通过身份验证的后续请求中需要包含什么内容?
  • 服务器是否必须对从此处开始的每个请求进行身份验证,并将其绑定回该特定用户?

0 个答案:

没有答案