1

我正在將DotNet 4.5 MVC/WebAPI應用程序轉換爲AspNetCore 2.0,並且在再次使我的Cookie身份驗證正常工作時遇到了一些麻煩。當我設置cookie並嘗試訪問安全的方法時,我無法到達那裏。當我進入一個匿名方法並檢查用戶對象時,它是空的 - 沒有認證類型,沒有聲明等。AspNetCore 2.0聲明總是爲空

我已經按照這篇文章盡我所能:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x。我沒有使用身份。

我在startup.cs ConfigureServices代碼如下:

services.AddAuthentication("ACE_AUTH")      
        .AddCookie("ACE_AUTH", options => 
        { 
         options.AccessDeniedPath = "/Home/Index/"; 
         options.LoginPath = "/Home/Index/"; 
        }); 

我在配置方法代碼:

app.UseAuthentication(); 

時,這就是所謂的校長是完全填充。當我設置我的cookie:

await HttpContext.SignInAsync("ACE_AUTH", samlData.Principal); 

沒有我曾嘗試已引起我的要求試圖驗證用戶時展現出來。

+0

面臨同樣的問題。你弄明白了嗎? – Clement

+0

還沒有。我現在不得不轉向其他事情,但我很快就會回頭看看。 –

回答

0

以下是我的工作內容:我學到的大部分內容都來自this microsoft doc,但正如您所說,文檔似乎並未將您帶到這裏。

在startup.cs

public void ConfigureServices(IServiceCollection services) 
    { 
     ... 

     services.AddAuthentication("ACE_AUTH") 
     .AddCookie("ACE_AUTH", options => { 
      options.AccessDeniedPath = "/api/Auth/Forbidden"; 
      options.LoginPath = "/"; 
      options.Cookie.Expiration = new TimeSpan(7,0,0,0); 
     }); 
    } 


public void Configure(IApplicationBuilder app, 
         IHostingEnvironment env, 
         ILoggerFactory loggerFactory) 
    { 
     ... 

     app.UseAuthentication(); 
    } 

然後在你的控制器處理

認證:

[HttpPost()] 
    [Route("api/[Controller]/[Action]/")] 
    public async Task<JsonResult> Login([FromBody]Dictionary<string, string> loginData) 
    { 
     try 
     { 
      var loggedIn = true; 
      if (loggedIn) 
      { 
       var claims = new List<Claim> { 
        new Claim(ClaimTypes.Name, "John Doe") 
       }; 

       var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); 
       identity.AddClaims(claims); 
       ClaimsPrincipal principal = new ClaimsPrincipal(identity); 

       await HttpContext.SignInAsync(
        "ACE_AUTH", 
        principal, 
        new AuthenticationProperties 
        { 
         IsPersistent = true, 
         ExpiresUtc = DateTime.UtcNow.AddDays(7) 
        }); 
      } 
      return new JsonResult(logRtn); 
     } 
     catch (Exception ex) 
     { 
      return new JsonResult(ex.Message); 
     } 
    } 

如果你可以驗證並分配的loggedIn您的身份驗證請求的結果,你應該能夠將聲明存儲在Cookie中。然後,您可以使用以下方式在控制器中回想可能正在執行授權/調用值的聲明:

[HttpGet("[Action]", Name = "GetSomething")] 
    [Route("[Action]")] 
    public JsonResult something() 
    { 
     try 
     { 
      var loggedInUser = HttpContext.User; 
      var claym = loggedInUser.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name); 
      if (claym != null) 
      { 
       return new JsonResult(claym.Value); 
       // returns "John Doe" 
      } 
      else 
      { 
       return new JsonResult(""); 
      } 
     } 
     catch (Exception ex) 
     { 
      return new JsonResult(ex.Message); 
     } 
    }