我在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" });
});
}
您說得對,User對象實際上只在[Authorize]塊中有意義。然而,這些塊然後根本不執行 - 因此我更改了測試授權到允許匿名。通過使用AllowAnonymous,我發現User.Identity不爲空(當我沒有登錄時)(刪除所有cookie) - 但是一旦我登錄,User.Identity就爲空。實際上,我會反過來期待這種行爲。 –
我作爲ClaimsPrincipal在用戶上得到空值。我嘗試在方法/控制器上添加Authorize/AllowAnonymous – Mohan