user.identity.getuserid = null但用户名有效

时间:2015-04-09 22:06:51

标签: .net asp.net-mvc authentication identity

我现在看几天来解决这个问题。 使用user.identity.name或user.identity.username登录后我得到了正确的值。

但是,当我想知道用户ID时,我得到一个null。

一切正常我可以登录我可以通过user.identity.name看到我的用户名 但是当我想看到我的用户ID然后我得到一个空的,有人知道这个问题是什么?

我的用户类Gebruiker == User

{
    [DataContract]

    public partial class Gebruiker
    {
          [DataMember]
        [Key]
          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     //   public short GebruikerId { get; set; }
            public int GebruikerId { get; set; }

        //  [ForeignKey("Role")]
        //  public long RoleId { get; set; }

        //  [ForeignKey("klanten")]
        // public long KlantId { get; set; }
          [DataMember]
        [Required(ErrorMessage = "gebruikersnaam is vereist")]
        [Remote("doesUserNameExist", "Gebruiker", HttpMethod = "POST", ErrorMessage = "gebruiker bestaat alreeds")]
        public string Gebruikersnaam { get; set; }

        [DataMember]
        [Required(ErrorMessage = "Wachtword is vereist")]
        public string WachtwoordHash { get; set; }

        [DataMember]
        [Required(ErrorMessage = "Naam is verplicht")]
        public string Naam { get; set; }

        [DataMember]
        public string Voornaam { get; set; }

        [DataMember]
        [Required(ErrorMessage = "Een Email is verplicht")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Het emailadres is niet geldig")]
        public string Email { get; set; }


       // [Required]
    //    public ICollection<Role> Roles { get; set; }
        public virtual ICollection<GebruikerRoles> GebruikerRoles { get; set; }
        public virtual ICollection<Reservatie> Reservatie { get; set; }







    }

制品

public class Artikel
    {

        [Key]
        [Required]
        //  [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public long ArtikelId { get; set; }

        [ForeignKey("Categorie")]
        [Required(ErrorMessage = "U bent verplict een categorie te selecteren")]
        public long CategorieId { get; set; }


        [StringLength(125, ErrorMessage = "max 125 tekens")]
        public string Naam { get; set; }

        public string Beschrijving { get; set; }

        public int max_uitleentermijn { get; set; }

        [StringLength(13,ErrorMessage = "Ean-13 Barcode kan max 13 tekens bevatten")]
        public string Barcode{get;set;}
        public string FiguurURL { get; set; }

     //   public ImageMap Image { get; set; }
        public byte[] byteImage { get; set; }

        public virtual Categorie Categorie { get; set; }

        public virtual ICollection<ReservatieDetail> ReservatieDetail { get; set; }
    }
}

类别

  public class Categorie
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long CategorieId { get; set; }

        [Required(ErrorMessage = "Categorie Naam is verplicht")]
        public string Naam { get; set; }
        public string Beschrijving { get; set; }


        public virtual Opleiding Opleiding { get; set; }
        public List<Artikel> Artikel1 { get; set; }



    }
}

的UserRole

public class GebruikerRoles
    {

        [Key]
        public int UserRoleId { get; set; }
        public int GebruikerId { get; set; }
        public long RoleId { get; set; }

        public virtual Role Role { get; set; }
    }
}


 public class Opleiding
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long OpleidingId { get; set; }

        public string OpleidingNaam { get; set; }
        // public string Naam { get; set; }
        //  public string Voornaam { get; set; }

        public List<Categorie> Categorie1 { get; set; }
        //  public List<Klant> klanten { get; set; }
        //public List<Gebruiker> gebruiker { get; set; }

        // public List<Leverancier> Leveranciers { get; set; }



    }

预订

  public class Reservatie
    {

 /*       public Reservatie()
        {
           this.ReservatieDetail = new HashSet<ReservatieDetail>();
  *///      }
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int reservatie_id { get; set; }
        public Guid GebruikerId { get; set; }

        public long ArtikelId { get; set; }
        public System.DateTime Datum { get; set; }

        public DateTime startdatum { get; set; }
        public DateTime einddatum { get; set; }

        public virtual Gebruiker Gebruiker { get; set; }
        public virtual Artikel Artikel { get; set; }
     //   public virtual ICollection<ReservatieDetail> ReservatieDetail { get; set; }
    }
}

作用

  public class Role
    {
        [Key]
        public long RoleId { get; set; }
        public string Naam { get; set; }

      //  public ICollection<Gebruiker> Gebruikers { get; set; }
    }

我的存储库类

  public class GebruikerRepository
    {
        private ReserveringContext context;

        public GebruikerRepository(ReserveringContext c)
        {
            this.context = c;
        }



        public ICollection<Gebruiker> GetAllUsersWithRoles()
        {
            return context.gebruiker
                .Include("Roles")
                .OrderBy(u => u.Naam)
                .ThenBy(u => u.Voornaam)
                .ToList();

        }

        public Gebruiker GetUserByUsernameAndPassword(string Gebruikersnaam, string wachtwoord)
        {
            //wachtwoord omzetten naar md5
            string hashedpass = FormsAuthentication.HashPasswordForStoringInConfigFile(wachtwoord, "md5");

            Gebruiker user = context.gebruiker
                .Include("GebruikerRoles")
                .Where(u => u.Gebruikersnaam.ToUpper() == Gebruikersnaam.ToUpper() &&
                            u.WachtwoordHash == hashedpass)
                .FirstOrDefault();




            return user;

        }




    }

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string cookieName = FormsAuthentication.FormsCookieName;

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated ||
                filterContext.HttpContext.Request.Cookies == null ||
                filterContext.HttpContext.Request.Cookies[cookieName] == null
            )
            {
                HandleUnauthorizedRequest(filterContext);
                return;
            }

            var authCookie = filterContext.HttpContext.Request.Cookies[cookieName];
            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            string[] roles = authTicket.UserData.Split(',');

            var userIdentity = new GenericIdentity(authTicket.Name);
            var userPrincipal = new GenericPrincipal(userIdentity, roles);

            filterContext.HttpContext.User = userPrincipal;
            base.OnAuthorization(filterContext);
        }
    }



    }

我的DBcontext

   public class ReserveringContext : DbContext
        {

            public DbSet<Artikel> Artikel { get; set; }
           public DbSet<Reservatie> Reservatie { get; set; }
            public DbSet<ReservatieDetail> ReservatieDetail { get; set; }
            public DbSet<Categorie> Categorie { get; set; }
            public DbSet<Gebruiker> gebruiker { get; set; }
            public DbSet<Role> Role { get; set; }
            public DbSet<Opleiding> Opleiding { get; set; }

            public DbSet<GebruikerRoles> GebruikerRole { get; set; }


}

我登录的控制器

public ActionResult Index()
        {
            var test = User.Identity.GetUserName();
            var test2 = User.Identity.GetUserId();
            var test3 = User.IsInRole("Administrator");
            var test4 = Roles.IsUserInRole("Administrator");
            var roles = ((ClaimsIdentity)User.Identity).Claims
                .Where(c => c.Type == ClaimTypes.Role)
                .Select(c => c.Value);
            return View();
        }

        public ActionResult Login()
        {
            LoginVM model = new LoginVM();
            return View(model);

        }

        [HttpPost]
        public ActionResult Login(LoginVM model, string returnurl)
        {

            if (ModelState.IsValid)
            {
                 Gebruiker logged_in_user = gebruikerrepository.GetUserByUsernameAndPassword(model.Gebruikersnaam, model.wachtwoord);


            //    var newuser = gebruikerrepository.GetUserByUsernameAndPassword(model.Gebruikersnaam, model.wachtwoord);
                if (logged_in_user != null)
                {

                    IEnumerable<string> rolenames = logged_in_user.GebruikerRoles.Select<GebruikerRoles, string>(r => r.Role.Naam);


                    string rolesstring = string.Join(";", rolenames.ToArray());


                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        logged_in_user.Gebruikersnaam,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                        model.RememberMe,
                        rolesstring
                    );




                    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                    var authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    Response.Cookies.Add(authcookie);

                    if (returnurl != null)
                    {
                        return Redirect(returnurl);
                    }
                    else
                    {

                        TempData["loginBoodschap"] = "Welkom, <b>" + logged_in_user.Gebruikersnaam + "</b>.<br />U bent nu ingelogd.";
                        User.Identity.GetUserId();
                        string gebruiker;
                        Gebruiker k = new Gebruiker();
                        gebruiker = model.Gebruikersnaam;
                        //   k = JsonConvert.DeserializeObject<Gebruiker>(model.Gebruikersnaam);
                        var json = JsonConvert.SerializeObject(logged_in_user.GebruikerId);
                        if (k != null)
                        {
                            HttpCookie newCookie = new HttpCookie("shop", json);
                            newCookie.Value = json;
                            DateTime now = DateTime.Now;
                            newCookie.Expires = now.AddMinutes(6000);
                            Response.Cookies.Add(newCookie);
                            TempData["boodschap"] = "U kunt nu starten met shoppen";



                            return RedirectToAction("Index", "Home");


                        }
                        else
                        {
                            TempData["boodschap"] = "Verkeerde gebruikersnaam en/of wachtwoord";
                            return RedirectToAction("Index", "Home");
                        }





                    }

                }
                else
                {

                    ModelState.AddModelError("", "De ingevoerde gebruikersnaam of wachtwoord is ongeldig");

                    return View(model);
                }

            }
            else
            {
                //onvolledige gegevens, toon formulier opnieuw
                return View(model);
            }


        }

1 个答案:

答案 0 :(得分:3)

我遇到了与OAuth相同的问题。 RequestContext.Principal.Identity.GetUserName()返回了用户名,但RequestContext.Principal.Identity.GetUserId()返回了null。

我查看了源代码,找到了原因:https://github.com/aspnet/Identity/blob/1c80580446132b6b5d9795930533aee8d6715006/src/Microsoft.AspNet.Identity.Security/IdentityExtensions.cs#L25-L38

原来我必须在用户登录时设置NameIdentifier声明。对我而言,这是GrantResourceOwnerCredentials

OAuthAuthorizationServerProvider方法
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

添加此声明后,GetUserId开始返回用户的ID。