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

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

问题描述

我有很多浏览网络上类似的网页,但大部分都使用一个新的项目,而不是现有的,或不具备必要的功能。所以,我有一个现有的MVC5项目,并希望整合的 ASP.NET MVC5身份与日志,电子邮件确认和密码重置功能。除此之外,我还需要创建所有的必需的数据库,即用户,角色,组等对表(我用EF code首先在我的项目)。是否有对应这些需要的物品或样品?任何建议将AP preciated。在此先感谢...

I have navigate lots of similar pages on the web, but most of them use a new project instead of an existing one, or not have the necessary features. So, I have an existing MVC5 project and want to integrate ASP.NET MVC5 Identity with log in, email confirmation and password reset features. 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 any article or sample that corresponds these needs? Any suggestion would be appreciated. Thanks in advance...

推荐答案

配置标识,以现有的项目也不是很难的事情。您必须安装一些的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 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 

添加一个用户类,并且使用 IdentityUser 继承:

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 
}

的DbContext 父窗体修改的DbContext IdentityDbContext< APPUSER> 是这样的:

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

如果你使用相同的连接字符串并启用迁移EF创建必要的表给你。

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

(可选),你可以多大程度上的UserManager 添加所需的配置和定制:

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

由于身份是基于OWIN需要配置OWIN太:

Since Identity is based on OWIN you need 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

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

几乎刚做这行code添加到您的的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>

现在在整个项目中,你可以使用Identity就像新的项目已经通过安装VS.例如,考虑登陆行动

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() {}

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

另外,你可以安装额外的包,并将其配置,以满足像 Microsoft.Owin.Security.Facebook 或任何你想你的要求。

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;

您还可以看到我其他的答案像<一个href=\"http://stackoverflow.com/questions/29988858/custom-authentication-and-authorization-based-on-user-rights/31755231#31755231\">this和<一个href=\"http://stackoverflow.com/questions/31846452/claim-based-authorization-design-for-conditional-edit-operation-in-asp-net-mvc-a/31851128#31851128\">this对于高级用途身份。

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

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

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