2016-11-04 60 views
2

我是.net核心的新手,並且從版本2/3起就沒有使用過ASP,因此與我一起裸露。使用API​​ .net核心進行身份驗證

我有以下設置。一個使用身份和令牌授權的Web API,包含整個用戶管理和當然一些額外的API調用。

此外,我正在構建一個FE以再次使用.net內核來使用API​​。我有我的登錄表單併發布到FE,該FE使用RestSharp執行API請求,提供我從表單獲得的憑據。我收到一些用戶數據和身份Cookie /令牌。 我將cookie/token設置爲響應,現在我的FE可以使用它來執行其他帶有ajax的API調用。

但我的問題是,我怎麼知道他在X分鐘後仍然登錄?如果Cookie /令牌過期,API調用將被拒絕,但我的FE-BE如何知道它們不再有效?我是否會檢查每個請求的有效期限? enter image description here

我在問這主要是爲了挑戰我構建系統的方式,以避免任何巨大的安全漏洞。

+0

稍微題外話:我建議'HttpClient'超過RestSharp。它完全建立在異步調用的基礎上,對單元測試有很大的支持,而RestSharp依賴於舊的'WebClient'和同步調用;至少它直到最近才這樣做。 – thoean

+0

@thoean謝謝你的提示,我會看看HttpClient,我剛剛發現RestSharp更易於使用。此外PostMan已自動翻譯成RestSharp :) – Drakoumel

回答

0

如果Cookie /令牌過期,API調用將被拒絕,但我的FE-BE如何知道它們不再有效?我是否會檢查每個請求的有效期限?

要確定授權訪問是否已過期,請檢查expires_in時間範圍optionally comes with an OpenID Connect implicit flow response.

  • access_token
  • token_type
  • id_token
  • state
  • expires_in可選。自生成響應以來,訪問令牌的過期時間(以秒爲單位)。

由於access_token對客戶端來說通常是不透明的,所以唯一的另一種查找訪問是否過期的方法是詢問發出者的access_token。

但我的問題是,我怎麼知道他在X分鐘後仍然登錄?

要確定您的用戶是否仍然登錄,請使用id_token而不是access_token

+0

thnx我現在正在工作,我會把我的解決方案作爲一個答案,如果你看看答案會很好。 (希望能儘快清理代碼) – Drakoumel

0

經過與朋友的一些交談,更合適的解決方案(在我看來)如下。 (該代碼可以清理)

 // 
    // POST: /Account/Login 
    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<IActionResult> Login(LoginViewModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      // Do a rest call to the API 
      Uri _baseUri = new Uri("http://localhost:8000/"); 
      var client = new RestClient(_baseUri + "api/Account/login"); 
      var request = new RestRequest(Method.POST); 
      request.AddHeader("postman-token", "7ee2a21b-70d5-8a68-f0dd-518b8a61ddbf"); 
      request.AddHeader("cache-control", "no-cache"); 
      request.AddHeader("content-type", "application/x-www-form-urlencoded"); 
      request.AddParameter("application/x-www-form-urlencoded", "Email=blah%40gmail.com&password=a1Aa1Aa1A!&=", ParameterType.RequestBody); 
      IRestResponse response = client.Execute(request); 

      // Check the response 
      if (response.StatusCode == HttpStatusCode.OK) { 
       // Grab the cookie for the Identity 
       // this can be replaced by a token in the future 
       String cookie = response.Cookies.Where(c => c.Name == ".AspNetCore.Identity.Application").First().Value; 
       // Store the cookie value to use it in sub-sequent requests     
       HttpContext.Session.SetString("IdentityCookieId", cookie); 


       // Add claims to our new user, an example Name and an example Role 
       const string Issuer = "http://blah.com"; 
       var claims = new List<Claim>(); 
       claims.Add(new Claim(ClaimTypes.Name, "AnonymUser", ClaimValueTypes.String, Issuer)); 
       claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer)); 

       var userIdentity = new ClaimsIdentity("SecuredLoggedIn"); 
       userIdentity.AddClaims(claims); 
       var userPrincipal = new ClaimsPrincipal(userIdentity); 

       // Sign in the user creating a cookie with X ammount of Expiry 
       await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, 
        new AuthenticationProperties 
        { 
         ExpiresUtc = DateTime.UtcNow.AddMinutes(1), 
         IsPersistent = false, 
         AllowRefresh = false 
        }); 

       // Move back to the ReturnUrl or for me always to the dashboard 
       return RedirectToLocal("/dashboard"); 
      } 
     } 

     return View(model); 
    } 

Ofcourse,你必須編輯Startup.cs文件ConfigureServices下您AddMvc()之前添加services.AddAuthorization();

而下Configure添加

 app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationScheme = "Cookie", 
      LoginPath = new PathString("/account/login/"), 
      AccessDeniedPath = new PathString("/Account/Forbidden/"), 
      AutomaticAuthenticate = true, 
      AutomaticChallenge = true 
     }); 
+0

@ShaunLuttin看看你是否有時間。 – Drakoumel

相關問題