c# – 在WebAPI和asp.net核心中使用基于Cookie的身份验证

场景:

我有一个解决方案,其中,我有WebAPI和Asp.Net核心MVC项目.我在WebAPI中实现了基于Cookie的身份验证.使用Postman进行测试时效果很好.但是,当我从我的MVC项目中使用WebAPI服务时,身份验证似乎被打破了.

这是我的代码:

的WebAPI:

Startup.cs

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AuthenticationScheme = "ApiAuth",
    AutomaticAuthenticate = true,
    AutomaticChallenge = false
});

AccountController.cs

[HttpPost]
[Route("authenticate")]
public IActionResult Authenticate([FromBody]LoginModel login)
{
    if (_accountManager.Authenticate(login))
    {
        var identity = new ClaimsIdentity("password");
        identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
        HttpContext.Authentication.SignInAsync("ApiAuth", new ClaimsPrincipal(identity)).Wait();
    }
    else
    {
        return Unauthorized();
    }
    return Ok(_accountManager.Authenticate(login));
}

所有控制器都具有此属性[Authorize(Roles =“User”)]

MVC应用程序:

AccountController.cs

public async Task<IActionResult> Login(LoginModel loginModel)
{
    var loginFlag = false;
    HttpResponseMessage response = await ServiceCall<LoginModel>.postData(URLPREFIX + "/authenticate", loginModel);
    if (response.IsSuccessStatusCode)
    {
        loginFlag = await response.Content.ReadAsAsync<bool>();
    }
    if (loginFlag)
    {
        return RedirectToAction("Index", "Home");
    }
    else
    {
        return View();
    }
}

ServiceCall.cs:

public static class ServiceCall<T>
    {
        static HttpClient client = new HttpClient();
        const string HTTP_BASE = "http://localhost:13359/";

        public static async Task<HttpResponseMessage> postData(string Url, T data)
        {
            HttpResponseMessage response = null;
            StringContent content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
            client.BaseAddress = new Uri(HTTP_BASE);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            response = await client.PostAsync(Url, content);
            return response;
        }
    }

这是我的截图:

《c# – 在WebAPI和asp.net核心中使用基于Cookie的身份验证》

WebAPI和MVC中的登录功能正在正确执行,但在导航到主页时,我无法使用该服务.任何意见将是有益的.谢谢.

更新#1:

这是my project repo的问题.请看一下.谢谢

最佳答案 我认为问题在这里:

 HttpResponseMessage response = await ServiceCall<LoginModel>.postData(URLPREFIX + "/authenticate", loginModel);
    if (response.IsSuccessStatusCode)
    {
        loginFlag = await response.Content.ReadAsAsync<bool>();
    }

您正在使用新的请求进行身份验证,此身份验证会在响应中写入cookie,当然不会对您的真实浏览器请求起作用.
您需要使用浏览器请求直接进行身份验证,让cookie写回客户端,然后您的客户端可以请求归属索引.

点赞