使用Cookie中的WebAPI的身份验证和asp.net核心
问题描述:
场景:使用Cookie中的WebAPI的身份验证和asp.net核心
我有一个解决方案,其中,我都和的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和mvc应用程序在不同的服务器上(如果你真的不能在应用程序中使用API认证),你可以自己谷歌的许多例子,你需要了解它,而不是有人写为你。 – Bucketcode
谢谢我的朋友。我用我的ServiceCall程序更新了我的问题。我正在使用的唯一新请求是'静态HttpClient客户端=新HttpClient();'。有没有办法使用相同的HttpClient而不创建新的? –