代码之家  ›  专栏  ›  技术社区  ›  marco birchler

为什么是用户。使用AspNet登录后标识为空。身份3.0

  •  1
  • marco birchler  · 技术社区  · 10 年前

    我使用的是微软AspNet。DNX RC1中的Identity 3.0框架。在一些教程的帮助下,我构建了一个自定义身份验证系统。密码检查成功后,将为用户创建一些声明,并将设置身份验证:

    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。标识。应用程序

    然而,我现在的身份确实有问题。注有[Authorize]的控制器根本不执行。使用[AllowAnonymous]的控制器会给我一个NullReferenceException,因为User。标识为空:

    [AllowAnonymous]
    [Route("api/trips")]
    public class TripController : Controller
    {
    
    [HttpGet("")]
    public JsonResult Get()
    {
        var trips = _repository.GetUserTripsWithStops(User.Identity.Name);
        ...
    
        return Json(results);
    }
    

    有人能告诉我我的身份验证有什么问题吗?

    我猜我的错误在创业公司的某个地方。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" });
        });
    }
    
    2 回复  |  直到 10 年前
        1
  •  2
  •   Chris Pratt    10 年前

    为了访问 User 对象,控制器/操作必须用 [Authorize] . [AllowAnonymous] 仅与 [授权] 。它本身什么也不做,因为默认情况下,匿名用户可以访问所有内容。

        2
  •  1
  •   niico    8 年前

    谢天谢地,经过一天多的试错,我找到了解决方案。最后,我在Startup中添加了AutomaticAuthenticate行。cs文件:

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