zoukankan      html  css  js  c++  java
  • Adding ASP.NET MVC5 Identity Authentication to an existing project

    Configuring Identity to your existing project is not hard thing. You must install some NuGet package and do some small configuration.

    First install these NuGet packages in Package Manager Console:

    PM> Install-Package Microsoft.AspNet.Identity.Owin 
    PM> Install-Package Microsoft.AspNet.Identity.EntityFramework
    PM> Install-Package Microsoft.Owin.Host.SystemWeb 
    

    Add a user class and with IdentityUser inheritance:

    public class AppUser : IdentityUser
    {
        //add your custom properties which have not included in IdentityUser before
        public string MyExtraProperty { get; set; }  
    }
    

    Do same thing for role:

    public class AppRole : IdentityRole
    {
        public AppRole() : base() { }
        public AppRole(string name) : base(name) { }
        // extra properties here 
    }
    

    Change your DbContext parent form DbContext to IdentityDbContext<AppUser> like this:

    public class MyDbContext : IdentityDbContext<AppUser>
    {
        // Other part of codes still same 
        // You don't need to add AppUser and AppRole 
        // since automatically added by inheriting form IdentityDbContext<AppUser>
    }
    

    If you use same connection string and enabled migration EF create necessary tables for you.

    Optionally you could extent UserManager to add your desired configuration and customization:

    public class AppUserManager : UserManager<AppUser>
    {
        public AppUserManager(IUserStore<AppUser> store)
            : base(store)
        {
        }
    
        // this method is called by Owin therefore best place to configure your User Manager
        public static AppUserManager Create(
            IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
        {
            var manager = new AppUserManager(
                new UserStore<AppUser>(context.Get<MyDbContext>()));
    
            // optionally configure your manager
            // ...
    
            return manager;
        }
    }
    

    Since Identity is based on OWIN you need configure OWIN too:

    Add a class to App_Start folder (or anywhere else if you want). This class is used by OWIN

    namespace MyAppNamespace
    {
        public class IdentityConfig
        {
            public void Configuration(IAppBuilder app)
            {
                app.CreatePerOwinContext(() => new MyDbContext());
                app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
                app.CreatePerOwinContext<RoleManager<AppRole>>((options, context) =>
                    new RoleManager<AppRole>(
                        new RoleStore<AppRole>(context.Get<MyDbContext>())));
    
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    LoginPath = new PathString("/Home/Login"),
                });
            }
        }
    }
    

    Almost done just add this line of code to your web.config file so OWIN could find your startup class.

    <appSettings>
        <!-- other setting here -->
        <add key="owin:AppStartup" value="MyAppNamespace.IdentityConfig" />
    </appSettings>
    

    Now in entire project you could use Identity just like new project had already installed by VS. Consider login action for example

    [HttpPost]
    public ActionResult Login(LoginViewModel login)
    {
        if (ModelState.IsValid)
        {
            var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
            var authManager = HttpContext.GetOwinContext().Authentication;
    
            AppUser user = userManager.Find(login.UserName, login.Password);
            if (user != null)
            {
                var ident = userManager.CreateIdentity(user, 
                    DefaultAuthenticationTypes.ApplicationCookie);
                AuthManager.SignIn(
                    new AuthenticationProperties { IsPersistent = false }, ident);
                return Redirect(login.ReturnUrl ?? Url.Action("Index", "Home"));
            }
        }
        ModelState.AddModelError("", "Invalid username or password");
        return View(login);
    }
    

    You could make roles and add to your users:

    public ActionResult CreateRole(string roleName)
    {
        var roleManager=HttpContext.GetOwinContext().GetUserManager<RoleManager<AppRole>>();
    
        if (!roleManager.RoleExists(roleName))
            roleManager.Create(new AppRole(roleName));
        // rest of code
    } 
    

    You could add any role to any user like this:

    UserManager.AddToRole(UserManager.FindByName("username").Id, "roleName");
    

    By using Authorize you could guard your actions or controllers:

    [Authorize]
    public ActionResult MySecretAction() {}
    

    or

    [Authorize(Roles = "Admin")]]
    public ActionResult MySecretAction() {}
    

    Also you could install additional package and configure them to meet your requirement like Microsoft.Owin.Security.Facebook or whichever you want.

    Note: Don't forget add relevant namespaces to your files:

    using Microsoft.AspNet.Identity;
    using Microsoft.Owin.Security;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.Owin;
    using Microsoft.Owin.Security.Cookies;
    using Owin;
    

    You could also see my other answers like this and this for advanced use of Identity.

    Adding ASP.NET MVC5 Identity Authentication to an existing project

  • 相关阅读:
    这可能是全网最全的流媒体知识科普文章
    JavaCV实战专栏文章目录(JavaCV速查手册)
    JavaCV复杂滤镜filter特效处理入门教程和常用案例汇总
    【PC桌面软件的末日,手机移动端App称王】写在windows11支持安卓,macOS支持ios,龙芯支持x86和arm指令翻译
    如何在龙芯架构和国产化操作系统平台上运行javacv
    如何在国产龙芯架构平台上运行c/c++、java、nodejs等编程语言
    JavaCV开发详解之35:使用filter滤镜实现画中画,以屏幕画面叠加摄像头画面为例
    JavaCV开发详解之34:使用filter滤镜实现字符滚动和无限循环滚动字符叠加,跑马灯特效制作
    JavaCV开发详解之33:使用filter滤镜实现动态日期时间叠加
    JavaCV开发详解之32:使用filter滤镜实现中文字符叠加
  • 原文地址:https://www.cnblogs.com/dupeng0811/p/adding-asp-net-mvc5-identity-authentication-to-an-existing-project.html
Copyright © 2011-2022 走看看