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

Adding ASP.NET MVC5 Identity Authentication to an existing project的更多相关文章

  1. 在ASP.NET MVC5 及 Visual Studio 2013 中为Identity账户系统配置数据库链接及Code-First数据库迁移

    在ASP.NET MVC5 及 Visual Studio 2013 中为Identity账户系统配置数据库链接及Code-First数据库迁移 最近发布的ASP.NET MVC 5 及Visual ...

  2. 坎坷路:ASP.NET 5 Identity 身份验证(上集)

    之所以为上集,是因为我并没有解决这个问题,写这篇博文的目的是纪录一下我所遇到的问题,以免自己忘记,其实已经忘了差不多了,写的过程也是自己回顾的过程,并且之前收集有关 ASP.NET 5 身份验证的书签 ...

  3. ASP.NET MVC5 网站开发实践(二) Member区域 - 用户部分(2)用户登录、注销

    上次实现了用户注册,这次来实现用户登录,用到IAuthenticationManager的SignOut.SignIn方法和基于声明的标识.最后修改用户注册代码实现注册成功后直接登录. 目录: ASP ...

  4. ASP.NET MVC5 网站开发实践(二) Member区域 - 用户部分(1)用户注册

    上一次把基本框架搭建起来了,这次开始整Web部分,终于可以看到界面了小激动一下.web项目部分从用户功能开始,基本有注册,登录.注销.查找.查看.删除等涉及Member区域和Manage区域. 目录: ...

  5. ASP.NET 5 Identity

    ASP.NET 5 Identity   “跌倒了”指的是这一篇博文:爱与恨的抉择:ASP.NET 5+EntityFramework 7 如果想了解 ASP.NET Identity 的“历史”及“ ...

  6. ASP.NET MVC5 高级编程-学习日记-第一章 入门

    1.1 ASP.NET MVC 简介 ASP.NET是一种构建Web应用程序的框架,它将一般的MVC(Model-View-Controller)模式应用于ASP.NET框架. 1.1.1 MVC模式 ...

  7. ASP.NET MVC5 网站开发实践(二) Member区域–我的咨询列表及添加咨询

    上次把咨询的架构搭好了,现在分两次来完成咨询:1.用户部分,2管理部分.这次实现用户部分,包含两个功能,查看我的咨询和进行咨询. 目录: ASP.NET MVC5 网站开发实践 - 概述 ASP.NE ...

  8. ASP.NET MVC5 网站开发实践(二) Member区域 - 修改及删除文章

    上次做了显示文章列表,再实现修改和删除文章这部分内容就结束了,这次内容比较简单,由于做过了添加文章,修改文章非常类似,就是多了一个TryUpdateModel部分更新模型数据.   目录: ASP.N ...

  9. ASP.NET MVC5 网站开发实践(二) Member区域 - 添加文章

    上次把架构做好了,这次做添加文章.添加文章涉及附件的上传管理及富文本编辑器的使用,早添加文章时一并实现. 要点: 富文本编辑器采用KindEditor.功能很强大,国人开发,LGPL开源,自己人的好东 ...

随机推荐

  1. 编程菜鸟的日记-初学尝试编程-C++ Primer Plus 第4章编程练习9

    #include <iostream>#include <string>using namespace std;struct CandyBar{ //string kind;  ...

  2. .net 4.0 中的特性总结(四):Tuple类型

    Tuple是具有指定数量和顺序的值的一种数据结构.针对这种数据结构,.Net4.0中提供了一组Tuple类型,具体如下: Tuple   Tuple<T>   Tuple<T1, T ...

  3. 学习Struts--Chap05:值栈和OGNL

    1.值栈的介绍 1.1 值栈的介绍: 值栈是对应每一个请求对象的数据存储中心,struts2会给每一个请求对象创建一个值栈,我们大多数情况下不需要考虑值栈在哪里,里面有什么,只需要去获取自己需要的数据 ...

  4. 【织梦dedecms安全设置】dedecms如何防止被黑?dedecms被黑了怎么办?

    [织梦dedecms安全设置]dedecms如何防止被黑?dedecms被黑了怎么办?010-63495805很多所谓的“黑客”都是用工具来扫描入侵,厉害点的人是不屑来黑我们的小网站的,所以我们一般做 ...

  5. JS_高程4.变量,作用域和内存问题(3)垃圾收集

    JavaScript的自动垃圾收集机制 执行环境会负责管理代码执行过程中使用的内存,编写JavaScript程序时,所需内存的分配以及无用内存的回收完全实现自动管理. 原理: 找出那些不再继续使用的变 ...

  6. pygame-KidsCanCode系列jumpy-part16-enemy敌人

    接上回继续,这次我们要给游戏加点难度,增加几个随机出现的敌人,玩家碰到敌人后Game Over. 最终效果如下,头上顶个"电风扇"的家伙,就是敌人. 一.先定义敌人类 # 敌人类 ...

  7. Java示例:如何执行进程并读取输出

    下面是一个例子,演示如何执行一个进程(类似于在命令行下键入命令),读取进程执行的输出,并根据进程的返回值判断是否执行成功.一般来说,进程返回 0 表示执行成功,其他值表示失败. import java ...

  8. Unity设置播放模式下始终先执行指定的场景

    通过我们使用Unity开发游戏,是在PC/Mac上.而一个游戏通常也会有很多的场景,比如A.B.C.D三个场景,正常流程下的执行顺序是 A –> B –> C –> D.在具体一点, ...

  9. Cocos Creator脚本开发事例

    HelloWorld.js window.Global = { gint: 168, }; cc.Class({ extends: cc.Component, properties: { label: ...

  10. SQLAlchemy——获取某列为空的数据

    session.query(StockAllInfo).filter( StockAllInfo.ts_code == tsCode and StockAllInfo.py_code==None).a ...