博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Adding ASP.NET MVC5 Identity Authentication to an existing project
阅读量:6296 次
发布时间:2019-06-22

本文共 4774 字,大约阅读时间需要 15 分钟。

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.EntityFrameworkPM> 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
{ // Other part of codes still same // You don't need to add AppUser and AppRole // since automatically added by inheriting form IdentityDbContext
}

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
{ public AppUserManager(IUserStore
store) : base(store) { } // this method is called by Owin therefore best place to configure your User Manager public static AppUserManager Create( IdentityFactoryOptions
options, IOwinContext context) { var manager = new AppUserManager( new UserStore
(context.Get
())); // 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.Create); app.CreatePerOwinContext
>((options, context) => new RoleManager
( new RoleStore
(context.Get
()))); 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.

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
(); 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
>(); 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 and for advanced use of Identity.

转载地址:http://ewmta.baihongyu.com/

你可能感兴趣的文章
不要将时间浪费到编写完美代码上
查看>>
《算法基础:打开算法之门》一3.4 归并排序
查看>>
高德开放平台开放源代码 鼓励开发者创新
查看>>
《高并发Oracle数据库系统的架构与设计》一2.5 索引维护
查看>>
Firefox 是 Pwn2own 2014 上攻陷次数最多的浏览器
查看>>
阿里感悟(十八)- 应届生Review
查看>>
话说模式匹配(5) for表达式中的模式匹配
查看>>
《锋利的SQL(第2版)》——1.7 常用函数
查看>>
jquery中hover()的用法。简单粗暴
查看>>
线程管理(六)等待线程的终结
查看>>
spring boot集成mongodb最简单版
查看>>
DELL EqualLogic PS存储数据恢复全过程整理
查看>>
《Node.js入门经典》一2.3 安装模块
查看>>
《Java 开发从入门到精通》—— 2.5 技术解惑
查看>>
Linux 性能诊断 perf使用指南
查看>>
实操分享:看看小白我如何第一次搭建阿里云windows服务器(Tomcat+Mysql)
查看>>
Sphinx 配置文件说明
查看>>
数据结构实践——顺序表应用
查看>>
python2.7 之centos7 安装 pip, Scrapy
查看>>
机智云开源框架初始化顺序
查看>>