将ASP.NET MVC5身份验证添加到现有项目

时间:2015-08-12 08:55:21

标签: asp.net asp.net-mvc authentication asp.net-identity owin

我在网上看过很多类似的网页,但大多数网页使用的是新项目而不是现有项目,或者没有必要的功能。所以,我有一个现有的 package com.foretell.lukas.spamedprick; import android.graphics.Bitmap; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; public class MainActivity extends AppCompatActivity { ArrayList<EditText> tfa = new ArrayList<EditText>(); int x = 0; boolean tf = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // References to XML widgets final RelativeLayout rl = (RelativeLayout) findViewById(R.id.background); final Button daButton = (Button) findViewById(R.id.button); Button restartButton = (Button) findViewById(R.id.restartButton); final EditText ruta1 = (EditText) findViewById(R.id.editText); final EditText ruta2 = (EditText) findViewById(R.id.editText2); final EditText ruta3 = (EditText) findViewById(R.id.editText3); final EditText ruta4 = (EditText) findViewById(R.id.editText4); final TextView outputText = (TextView) findViewById(R.id.outputText); tfa.add(ruta1); tfa.add(ruta2); tfa.add(ruta3); tfa.add(ruta4); final MediaPlayer mp = MediaPlayer.create(this, R.raw.spar); final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.hurra); daButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { if(tf) { daButton.setEnabled(false); mp.start(); try { tf = false; Thread.sleep(2000); } catch (InterruptedException e) { e.getStackTrace(); outputText.setText("Nått gick åt h***ete!"); } Collections.shuffle(tfa); x++; if (x <= 2) { outputText.setText("Det är inte " + tfa.get(0).getText() + "..."); tfa.get(0).setText(""); tfa.remove(0); } else if (x == 3) { outputText.setText("Det är..."); } else if (x == 4) { tfa.get(1).setText(""); tfa.remove(1); outputText.setText("Det är " + tfa.get(0).getText() + "!"); mp2.start(); } tf = true; daButton.setEnabled(true); }else{ System.out.println("YO!"); } } } ); restartButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { tfa.add(ruta1); tfa.add(ruta2); tfa.add(ruta3); tfa.add(ruta4); ruta1.requestFocus(); outputText.setText(""); x = 0; ruta1.setText(""); ruta2.setText(""); ruta3.setText(""); ruta4.setText(""); } } ); } } 项目,并希望将 ASP.NET MVC5身份与登录,电子邮件确认和密码重置功能集成。

除此之外,我还需要在数据库上创建所有必要的表,即用户,角色,组等(我在我的项目中使用EF Code First)。是否有符合这些需求的文章或样本?任何建议将不胜感激。提前谢谢......

4 个答案:

答案 0 :(得分:255)

为现有项目配置身份并不困难。您必须安装一些NuGet包并进行一些小配置。

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

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

为角色做同样的事情:

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

将您的DbContext家长从DbContext更改为IdentityDbContext<AppUser>,如下所示:

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将为您创建必要的表格。

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

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:

将一个类添加到App_Start文件夹(或任何其他地方,如果需要)。该类由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"),
            });
        }
    }
}

几乎只需将此行代码添加到web.config文件中,以便OWIN可以找到您的启动类。

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

现在在整个项目中,您可以使用Identity,就像VS已经安装的任何新项目一样。考虑登录操作,例如

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

您可以创建角色并添加到您的用户:

public ActionResult CreateRole(string roleName)
{
    var roleManager=HttpContext.GetOwinContext().GetUserManager<RoleManager<AppRole>>();

    if (!roleManager.RoleExists(roleName))
        roleManager.Create(new AppRole(roleName));
    // rest of code
} 

您还可以向用户添加角色,如下所示:

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

使用Authorize你可以保护你的行动或控制者:

[Authorize]
public ActionResult MySecretAction() {}

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

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

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

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,以便高级使用身份。

答案 1 :(得分:18)

这是我将Identity与现有数据库集成的方法。

  1. 使用MVC模板创建示例MVC项目。这包含Identity实现所需的所有代码 - Startup.Auth.cs,IdentityConfig.cs,Account Controller代码,Manage Controller,Models和相关视图。

  2. 为Identity和OWIN安装必要的nuget包。通过查看示例项目中的引用和@Sam

  3. 的答案,您将获得一个想法
  4. 将所有这些代码复制到现有项目中。请注意,不要忘记为Identity添加“DefaultConnection”连接字符串以映射到您的数据库。请检查IdentityModel.cs中的ApplicationDBContext类,您将在其中找到对“DefaultConnection”连接字符串的引用。

  5. 这是我在现有数据库上运行的SQL脚本,用于创建必要的表:

    USE ["YourDatabse"]
    GO
    /****** Object:  Table [dbo].[AspNetRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetRoles](
    [Id] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED 
    (
      [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserClaims]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserClaims](
       [Id] [int] IDENTITY(1,1) NOT NULL,
       [UserId] [nvarchar](128) NOT NULL,
       [ClaimType] [nvarchar](max) NULL,
       [ClaimValue] [nvarchar](max) NULL,
    CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED 
    (
       [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserLogins]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserLogins](
        [LoginProvider] [nvarchar](128) NOT NULL,
        [ProviderKey] [nvarchar](128) NOT NULL,
        [UserId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED 
    (
        [LoginProvider] ASC,
        [ProviderKey] ASC,
        [UserId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserRoles](
       [UserId] [nvarchar](128) NOT NULL,
       [RoleId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED 
    (
        [UserId] ASC,
        [RoleId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUsers]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUsers](
        [Id] [nvarchar](128) NOT NULL,
        [Email] [nvarchar](256) NULL,
        [EmailConfirmed] [bit] NOT NULL,
        [PasswordHash] [nvarchar](max) NULL,
        [SecurityStamp] [nvarchar](max) NULL,
        [PhoneNumber] [nvarchar](max) NULL,
        [PhoneNumberConfirmed] [bit] NOT NULL,
        [TwoFactorEnabled] [bit] NOT NULL,
        [LockoutEndDateUtc] [datetime] NULL,
        [LockoutEnabled] [bit] NOT NULL,
        [AccessFailedCount] [int] NOT NULL,
        [UserName] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
     GO
     ALTER TABLE [dbo].[AspNetUserClaims]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserLogins]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
     REFERENCES [dbo].[AspNetRoles] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
     GO
    
  6. 检查并解决任何剩余错误,您就完成了。身份将处理其余部分:)

答案 2 :(得分:3)

我建议IdentityServer。这是一个.NET Foundation项目,涉及许多有关身份验证和授权的问题。

概述

IdentityServer是一个基于.NET / Katana的框架和托管组件,允许使用OpenID Connect和OAuth2等协议为现代Web应用程序和API实现单点登录和访问控制。它支持广泛的客户端,如移动,Web,SPA和桌面应用程序,并且可扩展以允许集成到新的和现有的体系结构中。

有关详细信息,例如

  • 支持MembershipReboot和基于ASP.NET身份的用户存储
  • 支持其他Katana身份验证中间件(例如Google, Twitter,Facebook等)
  • 支持基于EntityFramework的配置持久性
  • 支持WS-Federation
  • 扩展

查看documentationsamples

答案 3 :(得分:0)

好吧,我知道我可能为时已晚。 这适用于那些已经做过一次或多次迁移的人。那些项目完美运行的人,那些在数据库中有 AspNet 表,但没有与这些相关的控制器、模型和视图的人。
我也遇到了同样的问题。我在开始时没有激活身份验证就开始了我的项目。然后我意识到我没有用于身份验证的所有元素(Views 文件夹中的 Account 和 Manage,控制器中的 accountController 和 ManageControler,以及模型中的 AccountViewModel 和 ManageViewModel)。 我刚刚创建了其他具有类似设置、名称的项目,并在创建该项目时激活了身份验证。 然后我设法将丢失的文件复制到我的初始项目中。 之后,我经历了每一次更改命名空间并导入到我的项目的命名空间