0

我在DNX RC1中使用了Microsofts AspNet.Identity 3.0框架。在一些教程的幫助下,我構建了一個自定義身份驗證系統。一個成功的密碼後查了一些索賠是用戶創建和認證將被設置:爲什麼在用AspNet.Identity 3.0登錄後User.Identity爲null

var claimsPrincipal = await SignInManager.CreateUserPrincipalAsync(user); 
if (claimsPrincipal != null && claimsPrincipal.Identity != null) 
{ 
    // Set the claims to the user 
    await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal); 
    return RedirectToAction("Index", "App"); 
} 

此登錄操作後,我的瀏覽器有兩個cookie:.AspNet.Cookies.AspNet.Microsoft.AspNet .Identity.Application

但是現在我的身份確實存在問題。用[Authorize]註釋的控制器完全不會執行。並通過[使用AllowAnonymous]控制器給我一個NullReferenceException因爲User.Identity爲空:

[AllowAnonymous] 
[Route("api/trips")] 
public class TripController : Controller 
{ 

[HttpGet("")] 
public JsonResult Get() 
{ 
    var trips = _repository.GetUserTripsWithStops(User.Identity.Name); 
    ... 

    return Json(results); 
} 

有人能告訴我什麼地方錯了我的認證?

正如我想,我的錯誤是某處Startup.cs文件 - 這裏是配置方法:

public void Configure(IApplicationBuilder app) 
{ 
    app.UseStaticFiles(); 

    app.UseIdentity(); 
    app.UseCookieAuthentication(options => 
    { 
     options.LoginPath = new PathString("/App/Login"); 
    }); 

    app.UseMvc(routes => 
    { 
     routes.MapRoute(
      name: "default", 
      template: "{controller}/{action}/{id?}", 
      defaults: new { controller = "App", action = "Index" }); 
    }); 
} 

回答

-1

感謝上帝我經過一天多的反覆試驗後發現瞭解決方案。最後,我在Startup.cs文件中添加了AutomaticAuthenticate行:

app.UseCookieAuthentication(options => 
{ 
    options.AutomaticAuthenticate = true; 
    options.LoginPath = new PathString("/App/Login"); 
}); 
0

爲了訪問User對象,控制器/行動必須符合[Authorize]裝飾。 [AllowAnonymous]僅與[Authorize]一起使用。就其本身而言,它不做任何事情,因爲默認情況下,匿名用戶可以訪問所有內容。

+0

您說得對,User對象實際上只在[Authorize]塊中有意義。然而,這些塊然後根本不執行 - 因此我更改了測試授權到允許匿名。通過使用AllowAnonymous,我發現User.Identity不爲空(當我沒有登錄時)(刪除所有cookie) - 但是一旦我登錄,User.Identity就爲空。實際上,我會反過來期待這種行爲。 –

+0

我作爲ClaimsPrincipal在用戶上得到空值。我嘗試在方法/控制器上添加Authorize/AllowAnonymous – Mohan

相關問題