android 获取asp.net web的cookie,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 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;

}

}

这是我的截图:

fab77dd3e59ced2fc28ea62cdc8c81c6.png

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

更新#1:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值