场景:
我有一个解决方案,其中,我有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 Login(LoginModel loginModel)
{
var loginFlag = false;
HttpResponseMessage response = await ServiceCall.postData(URLPREFIX + "/authenticate",loginModel);
if (response.IsSuccessStatusCode)
{
loginFlag = await response.Content.ReadAsAsync();
}
if (loginFlag)
{
return RedirectToAction("Index","Home");
}
else
{
return View();
}
}
ServiceCall.cs:
public static class ServiceCall
{
static HttpClient client = new HttpClient();
const string HTTP_BASE = "http://localhost:13359/";
public static async Task 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: