在 Web API 和 asp.net 核心中使用基于 Cookie 的身份验证
Using Cookies based authentication in WebAPI and asp.net core
场景:
我有一个解决方案,其中,我同时拥有 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;
}
}
这是我的截图:
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 写回客户端,然后您的客户端可以请求 home
index
.
场景:
我有一个解决方案,其中,我同时拥有 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;
}
}
这是我的截图:
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 写回客户端,然后您的客户端可以请求 home
index
.