3

場景:使用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; 
     } 
    } 

這裏是我的截圖:

enter image description here

兩個的WebAPI和MVC正確執行,但導航到主頁時,登錄功能,我無法使用服務。任何意見將是有益的。謝謝。

更新#1:

這裏是my project repo這一問題。請看一下。由於

回答

0

我覺得問題就在這裏:

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

您正在使用一個新的請求進行身份驗證,這身份驗證寫在響應一個cookie,當然不是工作在你真正的瀏覽器的請求。
您需要使用瀏覽器直接請求身份驗證,讓cookie寫回客戶端,然後您的客戶端可以請求homeindex

+0

感謝您的回覆。你能給我一個示例代碼嗎? –

+0

我不知道你的客戶端代碼,如果你的webapi和mvc應用程序在不同的服務器上(如果你真的不能在應用程序中使用API​​認證),你可以自己谷歌的許多例子,你需要了解它,而不是有人寫爲你。 – Bucketcode

+0

謝謝我的朋友。我用我的ServiceCall程序更新了我的問題。我正在使用的唯一新請求是'靜態HttpClient客戶端=新HttpClient();'。有沒有辦法使用相同的HttpClient而不創建新的? –

相關問題