Why is User.Identity null after login with AspNet.

2019-04-17 08:11发布

问题:

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