将 ASP.NET MVC5 身份验证添加到现有项目 [英] Adding ASP.NET MVC5 Identity Authentication to an existing project

查看:28
本文介绍了将 ASP.NET MVC5 身份验证添加到现有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网络上看到过很多类似的页面,但大多数都使用新项目而不是现有项目,或者没有必要的功能.因此,我有一个现有的 MVC 5 项目,并希望将 ASP.NET MVC5 Identity 与登录、电子邮件确认和密码重置功能集成起来.

I have seen lots of similar pages on the web, but most of them use a new project instead of an existing one, or don't have the necessary features. So, I have an existing MVC 5 project and want to integrate ASP.NET MVC5 Identity with log in, email confirmation and password reset features.

除此之外,我还需要在数据库上创建所有必要的表,即用户、角色、组等(我在我的项目中使用 EF Code First).是否有符合这些需求的文章或样本?

In addition to this, I also need to create all the necessary tables on the database i.e. User, Roles, groups, etc. (I use EF Code First in my project). Is there an article or sample that corresponds to these needs?

推荐答案

为现有项目配置 Identity 并不是一件难事.您必须安装一些 NuGet 包并进行一些小配置.

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

首先使用包管理器控制台安装这些 NuGet 包:

First install these NuGet packages with Package Manager Console:

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

添加一个用户类并带有IdentityUser继承:

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; }  
}

为角色做同样的事情:

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

将您的 DbContext 父级从 DbContext 更改为 IdentityDbContext,如下所示:

Change your DbContext parent from 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>
}

如果您使用相同的连接字符串并启用迁移,EF 将为您创建必要的表.

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

或者,您可以扩展 UserManager 以添加所需的配置和自定义:

Optionally, you could extend 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 this is the 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;
    }
}

由于 Identity 基于 OWIN,因此您也需要配置 OWIN:

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

将类添加到 App_Start 文件夹(或其他任何地方,如果需要).此类由 OWIN 使用.这将是您的创业班.

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

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"),
            });
        }
    }
}

即将完成,只需将这行代码添加到您的 web.config 文件中,以便 OWIN 可以找到您的启动类.

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>

现在在整个项目中,您可以像使用 VS 安装的任何新项目一样使用 Identity.以登录操作为例

Now in entire project you could use Identity just like any 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);
            //use the instance that has been created. 
            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 also add a role to a user, like this:

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

通过使用Authorize,您可以保护您的操作或控制器:

By using Authorize you could guard your actions or controllers:

[Authorize]
public ActionResult MySecretAction() {}

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

您还可以安装其他软件包并对其进行配置以满足您的要求,例如 Microsoft.Owin.Security.Facebook 或任何您想要的.

You can also install additional packages and configure them to meet your requirement like Microsoft.Owin.Security.Facebook or whichever you want.

注意:不要忘记将相关的命名空间添加到您的文件中:

Note: Don't forget to 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;

您还可以看到我的其他答案,例如 thisthis 用于身份的高级使用.

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

这篇关于将 ASP.NET MVC5 身份验证添加到现有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆