Why is User.Identity null after logging in with AspNet.Identity 3.0

I am using Microsoft AspNet.Identity 3.0 as part of DNX RC1. With the help of some tutorials, I created my own authentication system. After successful verification of the password, some claims are created for the user, and authentication will be established:

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 step, there are two cookies to enter my browser: .AspNet.Cookies and .AspNet.Microsoft.AspNet.Identity.Application

However, I now have a problem with my identity. Controllers annotated using [Authorization] are not executed at all. And the 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 happened to my authentication?

I suppose my error 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" }); }); } 
0
source share
2 answers

Thank goodness I found a solution after more than one day of trial and error. Finally, I simply added the AutomaticAuthenticate line in the Startup.cs file:

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

To access the User object, the controller / action must be decorated with [Authorize] . [AllowAnonymous] is only useful in conjunction with [Authorize] . At its core, it does nothing, because by default everything is available to anonymous users.

0
source

Source: https://habr.com/ru/post/1241116/


All Articles