Ho visto molte pagine simili sul web, ma la maggior parte di esse usa un nuovo progetto invece di uno esistente o non ha le funzionalità necessarie. Quindi, ho un progetto MVC 5
esistente e voglio integrare ASP.NET MVC5 Identity con login, e-mail di conferma e funzionalità di reimpostazione della password .
Oltre a questo, ho anche bisogno di creare tutte le tabelle necessarie sul database, ad esempio Utente, Ruoli, gruppi, ecc. (Uso il codice EF prima nel mio progetto). C’è un articolo o un campione che corrisponde a questi bisogni? Qualsiasi suggerimento sarebbe apprezzato. Grazie in anticipo…
La configurazione dell’identity framework per il tuo progetto esistente non è difficile. È necessario installare alcuni pacchetti NuGet e fare alcune piccole configurazioni.
Prima installa questi pacchetti NuGet nella Console di Gestione pacchetti:
PM> Install-Package Microsoft.AspNet.Identity.Owin PM> Install-Package Microsoft.AspNet.Identity.EntityFramework PM> Install-Package Microsoft.Owin.Host.SystemWeb
Aggiungi una class utente e l’ereditarietà di IdentityUser
:
public class AppUser : IdentityUser { //add your custom properties which have not included in IdentityUser before public string MyExtraProperty { get; set; } }
Fai la stessa cosa per il ruolo:
public class AppRole : IdentityRole { public AppRole() : base() { } public AppRole(string name) : base(name) { } // extra properties here }
Modifica il tuo DbContext
padre DbContext
DbContext
in IdentityDbContext
questo modo:
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 }
Se si utilizza la stessa stringa di connessione e la migrazione abilitata EF, creare le tabelle necessarie per l’utente.
Opzionalmente è ansible UserManager
per aggiungere la configurazione e la personalizzazione desiderate:
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; } }
Poiché Identity è basato su OWIN, devi configurare anche OWIN:
Aggiungi una class alla cartella App_Start
(o da qualsiasi altra parte se lo desideri). Questa class è usata da 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"), }); } } }
Fatto quasi tutto, aggiungi questa riga di codice al tuo file web.config
modo che OWIN possa trovare la tua class di avvio.
Ora nell’intero progetto è ansible utilizzare Identity proprio come il nuovo progetto era già stato installato da VS. Prendi in considerazione l’azione di login, ad esempio
[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); }
Puoi creare ruoli e aggiungere ai tuoi utenti:
public ActionResult CreateRole(string roleName) { var roleManager=HttpContext.GetOwinContext().GetUserManager>(); if (!roleManager.RoleExists(roleName)) roleManager.Create(new AppRole(roleName)); // rest of code }
Puoi aggiungere qualsiasi ruolo a qualsiasi utente come questo:
UserManager.AddToRole(UserManager.FindByName("username").Id, "roleName");
Utilizzando Authorize
puoi proteggere le tue azioni o i tuoi controllori:
[Authorize] public ActionResult MySecretAction() {}
o
[Authorize(Roles = "Admin")]] public ActionResult MySecretAction() {}
Inoltre, è ansible installare un pacchetto aggiuntivo e configurarli per soddisfare le proprie esigenze come Microsoft.Owin.Security.Facebook
o qualsiasi altra cosa si desideri.
Nota: non dimenticare di aggiungere spazi dei nomi rilevanti ai tuoi file:
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;
Potresti anche vedere le altre mie risposte come questa e questa per l’uso avanzato di Identity.
Questo è quello che ho fatto per integrare Identity con un database esistente.
Creare un progetto MVC di esempio con modello MVC. Questo ha tutto il codice necessario per l’implementazione di Identity: Startup.Auth.cs, IdentityConfig.cs, Codice controller account, Gestisci controller, Modelli e viste correlate.
Installa i pacchetti necessari di nuget per Identity e OWIN. Avrai un’idea vedendo i riferimenti nel progetto di esempio e la risposta di @ Sam
Copia tutti questi codici nel tuo progetto esistente. Nota: non dimenticare di aggiungere la stringa di connessione “DefaultConnection” per Identity da associare al tuo database. Controllare la class ApplicationDBContext in IdentityModel.cs in cui è presente il riferimento alla stringa di connessione “DefaultConnection”.
Questo è lo script SQL che ho eseguito sul mio database esistente per creare le tabelle necessarie:
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
Controlla e risolvi eventuali errori rimanenti e il gioco è fatto. L’id quadro gestirà il resto 🙂
Raccomando IdentityServer . Si tratta di un progetto di .NET Foundation e copre molti problemi relativi all’autenticazione e all’authorization.
IdentityServer è un framework basato su .NET / Katana e un componente hostable che consente l’implementazione di single sign-on e il controllo degli accessi per le moderne applicazioni Web e le API utilizzando protocolli come OpenID Connect e OAuth2. Supporta una vasta gamma di client come applicazioni mobili, web, SPA e desktop ed è estensibile per consentire l’integrazione in architetture nuove ed esistenti.
controlla la documentazione e i campioni .