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); 
     } 
    }