Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP身份2+;Web API令牌身份验证-未加载持久声明_C#_Authentication_Asp.net Web Api_Asp.net Identity_Asp.net Identity 2 - Fatal编程技术网

C# ASP身份2+;Web API令牌身份验证-未加载持久声明

C# ASP身份2+;Web API令牌身份验证-未加载持久声明,c#,authentication,asp.net-web-api,asp.net-identity,asp.net-identity-2,C#,Authentication,Asp.net Web Api,Asp.net Identity,Asp.net Identity 2,我在ASP.NET Web API令牌身份验证中遇到一些问题 基本上,我创建了一个具有一些声明的用户(值存储在AspNetUserClaim表中),但是当创建用户标识时,这些声明不会从数据库中提取出来 我的设置明细如下 用户类:有一个GenerateUserIdentityAsync方法(相当标准)和两个自定义属性: public class LibraryUser : IdentityUser{ //Add Custom Properties Here public strin

我在ASP.NET Web API令牌身份验证中遇到一些问题

基本上,我创建了一个具有一些声明的用户(值存储在AspNetUserClaim表中),但是当创建用户标识时,这些声明不会从数据库中提取出来

我的设置明细如下

  • 用户类:有一个GenerateUserIdentityAsync方法(相当标准)和两个自定义属性:

    public class LibraryUser : IdentityUser{
        //Add Custom Properties Here
        public string Company { get; set; }
    
        public string DisplayName { get; set; }
    
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<LibraryUser> manager, string authenticationType)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
    
            // Add custom user claims here
            return userIdentity;
        }
    }
    
    公共类库用户:IdentityUser{
    //在此处添加自定义属性
    公共字符串公司{get;set;}
    公共字符串DisplayName{get;set;}
    公共异步任务GenerateUserIdentityAsync(UserManager管理器,字符串身份验证类型)
    {
    //注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
    var userIdentity=wait manager.CreateIdentityAsync(这是authenticationType);
    //在此处添加自定义用户声明
    返回用户身份;
    }
    }
    
  • My DBContext声明了一些简单的名称更改,以使数据库看起来更好

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    
        // Modify the Model creation properties..
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    
        //Rename Identity 2.0 Tables to something nicer..
        modelBuilder.Entity<LibraryUser>().ToTable("LibraryUser");
        modelBuilder.Entity<IdentityUser>().ToTable("LibraryUser");
        modelBuilder.Entity<IdentityRole>().ToTable("Role");
        modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin");
    }
    
    模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
    {
    基于模型创建(modelBuilder);
    //修改模型创建属性。。
    modelBuilder.Conventions.Remove();
    //将Identity 2.0表重命名为更好的名称。。
    modelBuilder.Entity().ToTable(“LibraryUser”);
    modelBuilder.Entity().ToTable(“LibraryUser”);
    modelBuilder.Entity().ToTable(“角色”);
    modelBuilder.Entity().ToTable(“UserRole”);
    modelBuilder.Entity().ToTable(“UserClaim”);
    modelBuilder.Entity().ToTable(“UserLogin”);
    }
    
  • 我有一个名为LibraryUserManager的简单UserManager类,它只是为我的用户类型扩展了UserManager

    public class LibraryUserManager : UserManager<LibraryUser>
    
    公共类LibraryUserManager:UserManager
  • 对数据库进行种子设定时(调用更新数据库时),将创建以下用户:

    // -- Create Admin User, put in admin role..
    LibraryUserManager userManager = new LibraryUserManager(new UserStore<LibraryUser>(context));
    
    var user = new LibraryUser()
    {
        UserName = "admin@admin.com",
        Email = "admin@admin.com",
        DisplayName = "Administrator",
        Company = "Test"
    };
    
    userManager.Create(user, "Password1.");
    
    userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "user"));
    userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "author"));
    userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "reviewer"));
    userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "admin"));
    
    /--创建管理员用户,设置为管理员角色。。
    LibraryUserManager userManager=newlibraryusermanager(newuserstore(context));
    var user=new LibraryUser()
    {
    用户名=”admin@admin.com",
    电子邮件=”admin@admin.com",
    DisplayName=“管理员”,
    Company=“Test”
    };
    创建(用户“Password1”);
    userManager.AddClaim(user.Id,新声明(ClaimTypes.Role,“user”);
    userManager.AddClaim(user.Id,新声明(ClaimTypes.Role,“author”);
    userManager.AddClaim(user.Id,新声明(ClaimTypes.Role,“审阅者”);
    userManager.AddClaim(user.Id,新声明(ClaimTypes.Role,“admin”);
    
  • 一旦运行此命令。。数据库包含用户(在LibraryUser表中)和声明(在UserClaim表中)

  • 当用户通过我的自定义身份验证提供程序进行身份验证时(通过用户管理器)会找到用户,并调用GenerateUserIdentityAsync:
  • 编辑:显示该方法的其余部分

        var userManager = context.OwinContext.GetUserManager<LibraryUserManager>();
    
        LibraryUser user = await userManager.FindAsync(context.UserName, context.Password);
    
        //check if a user exists
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }
    
        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
        AuthenticationProperties properties = CreateProperties(user.UserName, user.DisplayName, oAuthIdentity);           
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
    
        context.Validated(ticket);
    
    var userManager=context.OwinContext.GetUserManager();
    LibraryUser=await userManager.FindAsync(context.UserName,context.Password);
    //检查用户是否存在
    if(user==null)
    {
    SetError(“无效的授权”,“用户名或密码不正确”);
    返回;
    }
    ClaimsIdentity oAuthIdentity=await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);
    AuthenticationProperties=CreateProperties(user.UserName、user.DisplayName、oAuthIdentity);
    AuthenticationTicket=新的AuthenticationTicket(OAuthidentitity,属性);
    上下文。已验证(票证);
    
  • 创建属性(如上所述)的内容:

    public static AuthenticationProperties CreateProperties(字符串用户名、字符串显示名、ClaimsIdentity oAuthIdentity)
    {
    IDictionary data=新字典
    {
    {“用户名”,用户名},
    {“displayName”,displayName},
    {“roles”,string.Join(“,”,oAuthIdentity.Claims.Where(c=>c.Type==ClaimTypes.Role)。选择(c=>c.Value.ToArray())}
    };
    返回新的AuthenticationProperties(数据);
    }
    
  • 当用户被授权时。。我在LibraryUser.GenerateUserIdentityAsync(上面第1点下的代码)中设置了一个断点,并且ClaimsEntity中只有声明。CreateIdentityAsync返回的声明集合是默认集合(名称、标识\u提供程序、安全\u戳记等)。。我手动添加的声明不会从DB返回

  • 有人能看到我错过了什么吗

    我已尝试提供所有信息,我可以如果你需要更多的请评论,我会修改我的问题

    提前感谢:D

    _L

    放入数据库的声明(您在
    AddClaim()
    中做过)和使包含在令牌中的声明是不同的。您必须手动将索赔数据放入继承的
    OAuthAuthorizationServerProvider
    类中,ASP.NET在Provider文件夹或您创建的任何oauth Provider中为其提供默认应用程序noauthProvider.cs

    在那里,重写的
    GrantResourceOwnerCredentials()
    方法没有
    AuthenticationTicket=newauthenticationTicket(oAuthIdentity,属性)以便将声明放入令牌中

    然后,Windows Identity将从您放置的令牌中读取声明

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var userManager = _container.GetInstance<ApplicationUserManager>())
            {
                var user = await userManager.FindAsync(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
    
                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                    context.Options.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    CookieAuthenticationDefaults.AuthenticationType);
                AuthenticationProperties properties = CreateProperties(user);
    
                // Below line adds additional claims in token.
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
    
    
        public static AuthenticationProperties CreateProperties(AspNetUser user)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                {"Id", user.Id.ToString(CultureInfo.InvariantCulture)},
                {"http://axschema.org/namePerson", user.Nickname,},
                {"http://axschema.org/contact/email", user.Email,},
            };
    
            return new AuthenticationProperties(data);
        }
    
    public override异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext)
    {
    使用(var userManager=\u container.GetInstance())
    {
    var user=await userManager.FindAsync(context.UserName,context.Password);
    if(user==null)
    {
    SetError(“无效的授权”,“用户名或密码不正确”);
    返回;
    }
    ClaimsIdentity oAuthIdentity=等待userManager.CreateIdentityAsync(用户,
    context.Options.AuthenticationType);
    ClaimSideEntity cookiesIdentity=await userManager.CreateIdentityAsyn
    
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var userManager = _container.GetInstance<ApplicationUserManager>())
            {
                var user = await userManager.FindAsync(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
    
                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                    context.Options.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    CookieAuthenticationDefaults.AuthenticationType);
                AuthenticationProperties properties = CreateProperties(user);
    
                // Below line adds additional claims in token.
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
    
    
        public static AuthenticationProperties CreateProperties(AspNetUser user)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                {"Id", user.Id.ToString(CultureInfo.InvariantCulture)},
                {"http://axschema.org/namePerson", user.Nickname,},
                {"http://axschema.org/contact/email", user.Email,},
            };
    
            return new AuthenticationProperties(data);
        }
    
    modelBuilder.Entity<LibraryUser>().ToTable("LibraryUser");
    modelBuilder.Entity<IdentityUser>().ToTable("LibraryUser"); // <-- this one