Why is User.Identity null after login with AspNet.Identity 3.0

末鹿安然 提交于 2019-12-06 12:45:53

问题


I am using Microsofts AspNet.Identity 3.0 framework within the DNX RC1. With the help of some tutorials I have built a custom authentication system. After a successful password check some claims are created for the user and the Authentication will be set:

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

After this login action my browser has two cookies: .AspNet.Cookies and .AspNet.Microsoft.AspNet.Identity.Application

However I do have now a problem with my identity. Controllers annotated with [Authorize] are not executed at all. And controllers with [AllowAnonymous] give me a NullReferenceException because User.Identity is null:

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

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

    return Json(results);
}

Can someone please tell me what's wrong with my authentication?

As I guess that my mistake is somewhere in the Startup.cs file - here is the configure method:

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:


In order to access the User object, the controller/action must be decorated with [Authorize]. [AllowAnonymous] is only useful in conjunction with [Authorize]. On its own it does nothing, as by default, everything is accessible to anonymous users.




回答2:


Thank god I have found the solution after more than one day trial and error. Finally I just added the AutomaticAuthenticate-line in the Startup.cs file:

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


来源:https://stackoverflow.com/questions/34879171/why-is-user-identity-null-after-login-with-aspnet-identity-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!