Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.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.NET 5编写自定义身份验证类_C#_Asp.net_Asp.net Identity - Fatal编程技术网

C# 为ASP.NET 5编写自定义身份验证类

C# 为ASP.NET 5编写自定义身份验证类,c#,asp.net,asp.net-identity,C#,Asp.net,Asp.net Identity,开箱即用的ASP.NET 5标识类是直截了当的,并且易于设置和使用,但是我的问题是,我使用的是一个遗留系统,其中包含现有的用户和权限表,我必须为其自定义标识系统。标识系统似乎非常可插拔,但我找不到任何关于如何编写自定义标识类的适当文档。是否有关于 如何编写自定义ASP.NET 5标识类,以满足遗留系统用户和权限表的需要 如何设置自定义标识类在ASP.NET 5、MVC 6应用程序中的使用 目前还没有太多可用文档,因此我使用了最新的标识类,即Microsoft.AspNet.Identity.En

开箱即用的ASP.NET 5标识类是直截了当的,并且易于设置和使用,但是我的问题是,我使用的是一个遗留系统,其中包含现有的用户和权限表,我必须为其自定义标识系统。标识系统似乎非常可插拔,但我找不到任何关于如何编写自定义标识类的适当文档。是否有关于

  • 如何编写自定义ASP.NET 5标识类,以满足遗留系统用户和权限表的需要
  • 如何设置自定义标识类在ASP.NET 5、MVC 6应用程序中的使用

  • 目前还没有太多可用文档,因此我使用了最新的标识类,即Microsoft.AspNet.Identity.EntityFramework 3.0.0-rc1-final,并提出了一个解决方案,可用于我的旧用户数据库表

    首先,确保您的旧用户实体类实现了
    IdentityUser
    类,以便我们可以在ASP.NET 5中使用该类进行身份验证

    public class MyLegacyUser : IdentityUser
    {
        // Your MyLegacyUser properties will go here as usual
    }
    
    确保忽略从
    IdentityUser
    类继承的任何不想使用的属性(这些属性不包含在用户表中)。我们通过在
    DbContext
    类的
    OnModelCreating
    方法中使用fluent api来实现这一点

    public class MyDbContext : DbContext
    {
        public DbSet<MyLegacyUser> MyLegacyUser { get; set; }
    
        // For simplicity I will add only the OnModelCreating method here
        protected override void OnModelCreating
        {
            modelBuilder.Entity<MyLegacyUser>(entity =>
            {
                entity.Ignore(e => e.AccessFailedCount);
                entity.Ignore(e => e.Claims);
                entity.Ignore(e => e.ConcurrencyStamp);
                entity.Ignore(e => e.Email);
                entity.Ignore(e => e.EmailConfirmed);
                entity.Ignore(e => e.Id);
                entity.Ignore(e => e.LockoutEnabled);
                entity.Ignore(e => e.LockoutEnd);
                entity.Ignore(e => e.Logins);
                entity.Ignore(e => e.NormalizedEmail);
                entity.Ignore(e => e.NormalizedUserName);
                entity.Ignore(e => e.PasswordHash);
                entity.Ignore(e => e.PhoneNumber);
                entity.Ignore(e => e.PhoneNumberConfirmed);
                entity.Ignore(e => e.Roles);
                entity.Ignore(e => e.SecurityStamp);
                entity.Ignore(e => e.TwoFactorEnabled);
            }
        }
    }
    
    完成后,我们必须实现自己的
    UserStore
    类。您可以实现一些接口,例如
    IUserStore
    IUserLoginStore
    iuserclaimstore
    等。我实现了
    iuserclaimstore
    接口,实现了
    GetUserIdAsync
    GetUserNameAsync
    FindByIdAsync
    GetClaimsAsync
    方法

    public class MyLegacyUserClaimStore : IUserClaimStore<MyLegacyUser>
    {
        // Here I simply returned the username of the user parameter I recieved as input
        public Task<string> GetUserIdAsync(MasterUser user, CancellationToken cancellationToken)
        {
            return Task.Run(() => user.UserName, cancellationToken);
        }
    }
    
    // Here I simply returned the username of the user parameter I recieved as input
    public Task<string> GetUserNameAsync(MasterUser user, CancellationToken cancellationToken)
    {
        return Task.Run(() => user.UserName, cancellationToken);
    }
    
    public Task<MasterUser> FindByIdAsync(string userId, CancellationToken cancellationToken)
    {
        // This is my manager class to read my user for the userId
        // Add your own code to read the user for the set Id here
        return Task.Run(() => new MyLegacyUserUserManager().ReadForEmailAddress(userId, 0, true, true), cancellationToken);
    }
    
     public Task<MasterUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
     {
         // This is my manager class to read my user for the normalizedUserName
        // Add your own code to read the user for the set normalizedUserName here
         return Task.Run(() => new MyLegacyUserManager().ReadForEmailAddress(normalizedUserName, 0, true, true), cancellationToken);
     }
    
    // If you want to make use of Claims make sure that you map them here
    // If you do not use claims, consider implementing one of the other IUserStore interfaces 
    //such as the IUserLoginStore so that you do not have to implement the GetClaimsAsync method
    public async Task<IList<Claim>> GetClaimsAsync(MasterUser user, CancellationToken cancellationToken)
    {
        var claims = new List<Claim>();
    
        foreach (var claim in user.Claims)
        {
            claims.Add(new Claim(claim.ClaimType, claim.ClaimValue));
        }
    
        return claims;
    }
    
    Configure
    方法中,确保指定要使用标识功能进行身份验证

    注意:使用语句的顺序很重要,如果使用Mvc,请确保在
    UseMvc
    之前包含
    UseIdentity

    public async void Configure(IApplicationBuilder app)
    {
        app.UseIdentity();
        // Your useMvc and other use statements will go here
    }
    
    现在,我们已经配置了自定义身份验证类,可以使用默认的
    SignInManager
    类进行身份验证。下面是我的
    AuthController
    类的一个示例

    public class AuthController : Controller
    {
        private SignInManager<MyLegacyUserUser> _signInManager;
    
        public AuthController(SignInManager<MasterUser> signInManager)
        {
            _signInManager = signInManager;
        }
    
        // For simplicity I will only add the Login action here
        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel)
        {
            var result = await _signInManager.PasswordSignInAsync(loginViewModel.Username, loginViewModel.Password, true, false);
    
            if (result == SignInResult.Success)
            {
                return RedirectToAction("Index", "SomeControllerToRedirectTo");
            }
    
            await _signInManager.SignOutAsync();
    
            return RedirectToAction("Login", "Auth");
        }
    }
    

    看一看。这里有一些自定义标识实现的示例。它是关于当前(MVC 5)版本的,但与ASP.Net身份相关的事情在ASP.vNext中没有太大变化。谢谢@AndyKorneyev,我会看一看
    public async void Configure(IApplicationBuilder app)
    {
        app.UseIdentity();
        // Your useMvc and other use statements will go here
    }
    
    public class AuthController : Controller
    {
        private SignInManager<MyLegacyUserUser> _signInManager;
    
        public AuthController(SignInManager<MasterUser> signInManager)
        {
            _signInManager = signInManager;
        }
    
        // For simplicity I will only add the Login action here
        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel)
        {
            var result = await _signInManager.PasswordSignInAsync(loginViewModel.Username, loginViewModel.Password, true, false);
    
            if (result == SignInResult.Success)
            {
                return RedirectToAction("Index", "SomeControllerToRedirectTo");
            }
    
            await _signInManager.SignOutAsync();
    
            return RedirectToAction("Login", "Auth");
        }
    }
    
    var email = User.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Email)).Value;