Fully utilizing MVC Owin identity with n(3)-tier architecture

前端 未结 1 1132
难免孤独
难免孤独 2021-01-19 15:19

I\'ve been learning out of the box Owin Identity and I love the ease of use it provides us with user management. Then problem that I have is that it interacts directly with

相关标签:
1条回答
  • 2021-01-19 15:59

    If you want to use existing database/tables, you do not have to use entire ASP.Net Identity. Instead, you can just use Owin Cookie Authentication middleware.

    I have working sample code at GitHub. If you want to test it, you just set a break-point at AccountController.cs, and return true.

    The followings are two main classes of configure the middleware and sign-in.

    Startup.cs

    public class Startup
    {
       public void Configuration(IAppBuilder app)
       {
          app.UseCookieAuthentication(new CookieAuthenticationOptions
          {
            AuthenticationType = "ApplicationCookie",
            LoginPath = new PathString("/Account/Login")
          });
       }
    }
    

    OwinAuthenticationService.cs

    public class OwinAuthenticationService : IAuthenticationService
    {
        private readonly HttpContextBase _context;
        private const string AuthenticationType = "ApplicationCookie";
    
        public OwinAuthenticationService(HttpContextBase context)
        {
            _context = context;
        }
    
        public void SignIn(User user)
        {
            IList<Claim> claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.GivenName, user.FirstName),
                    new Claim(ClaimTypes.Surname, user.LastName),
                };
    
            ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
    
            IOwinContext context = _context.Request.GetOwinContext();
            IAuthenticationManager authenticationManager = context.Authentication;
    
            authenticationManager.SignIn(identity);
        }
    
        public void SignOut()
        {
            IOwinContext context = _context.Request.GetOwinContext();
            IAuthenticationManager authenticationManager = context.Authentication;
    
            authenticationManager.SignOut(AuthenticationType);
        }
    }
    
    0 讨论(0)
提交回复
热议问题