对于没有包含认证(authentication),的项目,你可使用基架(scaffolder)把 Identity的程序集包加入到项目中,而且选择性的添加Identity的代码进行生成。css
虽然基架已经生成了不少必须的代码,可是你仍然须要更新你的项目来完善这个过程。html
这篇文章主要就是解释完善Identity基架进行更新的一些步骤jquery
当Identity基架添加之后,一个ScaffoldingReadme.txt 文件就被建立了,这里面会包含一些完善Identity基架的说明。以下web
ScaffoldingReadme.txt ajax
Support for ASP.NET Core Identity was added to your project 支持把ASP.NET Core Identity添加到你的项目里 - The code for adding Identity to your project was generated under Areas/Identity. 添加Identity生成的代码在Areas/Identity下面
关于Identity 相关的服务配置在Areas/Identity/IdentityHostingStartup.cs 中能够被找到 Configuration of the Identity related services can be found in the Areas/Identity/IdentityHostingStartup.cs file. UI须要支持静态文件,能够在Configure方法中调用 app.UseStaticFiles() The generated UI requires support for static files. To add static files to your app: 1. Call app.UseStaticFiles() from your Configure method
要使用ASP.NET Core Identity,你还须要容许认证(authentication),能够在Configure方法中调用 app.UseAuthentication(),在调用静态文件以后作此设置 To use ASP.NET Core Identity you also need to enable authentication. To authentication to your app: 1. Call app.UseAuthentication() from your Configure method (after static files)
UI 要求MVC,能够经过在 Configure 方法中调用app.UseMvc(),在认证以后调用,
另外还须要在 ConfigureServices 中增长调用 services.AddMvc() The generated UI requires MVC. To add MVC to your app: 1. Call services.AddMvc() from your ConfigureServices method 2. Call app.UseMvc() from your Configure method (after authentication) Apps that use ASP.NET Core Identity should also use HTTPS. To enable HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
这篇文章会提供更详细的说明sql
1.首先,准备一个空项目数据库
操做如图:bootstrap
2.添加Identity基架mvc
而后,选择文件;app
在这步,若是有布局页,能够选择现有的布局页;
这里没有没有布局页,也不须要指定一个新的布局页,就空着就能够了,它会自动生成一个新的布局页;
而后选择你须要的功能页面,这里选择的是登陆功能页面,登陆功能页面,注册功能页面;
再选择数据上下文,这里,若是存在的话,同样能够选择已经存在的;可是,在这个空项目中,是没有数据上下文的,因此这里直接点击加号,
新增一个便可。
点击添加
3.在StartUp文件类中,增长以下代码:
public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) {
//新增的代码 services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
//注释的为空项目中原来的代码 //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); //} //app.Run(async (context) => //{ // await context.Response.WriteAsync("Hello World!"); //}); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); //引入异常中间件,捕获以后出现的异常 } else { app.UseHsts(); //不是必须添加的,但推荐添加,以后会专门讲解,待续 }
//新增的代码 app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(); } }
注意,若是StartUp按照原来空项目的代码,去运行项目的话,像注册,登陆,登出等功能页面不能显示,只打印 Hello world;
这里从前面ScaffoldingReadme.txt 文件的说明也能看到,UI的显示须要静态文件和MVC等
4.迁移到数据库
生成的Identity数据库代码须要用到Entity Framework Core Migrations(EFCore的迁移)来建立一个迁移,并更新到数据库
以下:
Add-Migration CreateIdentitySchema
Update-Database
CreateIdentitySchema这个名字能够本身随意取,可是最好能作到见名知义,知道作了哪些迁移
以后,能够本身打开vs上的sql server 对象资源管理器查看数据库和表是否生成成功;
5.运行,查看效果
这里,要说下这个路径了,为何会是上图标示的这个路径呢
下面展现下目录结构,以下图:
即区域(Areas)下的 Identity/Account/Login
这里应该使用的是一种约定优先的路由方式,
这块以后可能会给出一篇讲解,这里先知道怎么找路由路径便可
注意,下面几个与第一个相似,就再也不给出详细图示,能够本身按步骤操做,若是有须要,后面再补充
1.首先,准备一个项目中原来不带认证的Razor项目
2.把Identity基架添加到项目中
这里操做同第一个,能够按需选择进行添加
3.迁移(Migrations),添加认证,布局
迁移
Add-Migration CreateIdentitySchema
Update-Database
容许认证
在StartUp文件的Configure方法中,在静态文件(UseStaticFiles)以后,调用 UseAuthentication
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAuthentication(); //添加认证 app.UseMvc(); } }
布局变化
在布局页面(the layout file)中增长登陆分页面(_LoginPartial)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - RazorNoAuth8</title> <environment include="Development"> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment exclude="Development"> <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css" asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" /> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a asp-page="/Index" class="navbar-brand">RazorNoAuth8</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a asp-page="/Index">Home</a></li> <li><a asp-page="/About">About</a></li> <li><a asp-page="/Contact">Contact</a></li> </ul> <partial name="_LoginPartial" /> </div> </div> </nav> <partial name="_CookieConsentPartial" /> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>© 2018 - RazorNoAuth8</p> </footer> </div> <environment include="Development"> <script src="~/lib/jquery/dist/jquery.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> </environment> <environment exclude="Development"> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js" asp-fallback-src="~/lib/jquery/dist/jquery.min.js" asp-fallback-test="window.jQuery" crossorigin="anonymous" integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk"> </script> <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js" asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js" asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal" crossorigin="anonymous" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"> </script> <script src="~/js/site.min.js" asp-append-version="true"></script> </environment> @RenderSection("Scripts", required: false) </body> </html>
1.首先准备一个项目中原来存在认证的项目
2.把Identity基架添加到项目中
注意,这里在选择布局这个页面操做时,你能够选择已经存在的布局哦,还有数据库上下文,也能够选择使用已经存在的,固然也能够新建
1.首先准备项目中原来不存在认证的MVC项目
2.把Identity基架添加到项目中
把登陆分页(_LoginPartial)添加到Views/Shared/_Layout.cshtml 中
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - MvcNoAuth3</title> <environment include="Development"> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment exclude="Development"> <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css" asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" /> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">MvcNoAuth3</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li> <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li> <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li> </ul> <partial name="_LoginPartial" /> </div> </div> </nav> <partial name="_CookieConsentPartial" /> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>© 2018 - MvcNoAuth3</p> </footer> </div> <environment include="Development"> <script src="~/lib/jquery/dist/jquery.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> </environment> <environment exclude="Development"> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js" asp-fallback-src="~/lib/jquery/dist/jquery.min.js" asp-fallback-test="window.jQuery" crossorigin="anonymous" integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk"> </script> <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js" asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js" asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal" crossorigin="anonymous" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"> </script> <script src="~/js/site.min.js" asp-append-version="true"></script> </environment> @RenderSection("Scripts", required: false) </body> </html>
而后,把 Pages/Shared/_LoginPartial.cshtml 移动到 Views/Shared/_LoginPartial.cshtml 位置
迁移
Add-Migration CreateIdentitySchema
Update-Database
添加认证
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvcWithDefaultRoute(); //使用mvc默认路由 } }
1.首先准备一个项目中本来存在认证(authentication)的MVC项目
2.把Identity基架添加到项目中
删除 Pages/Shared 下的文件,和这个目录
下面的代码展现了对比默认Identity UI的一些变化,你可能会想对Identity UI更彻底的控制。
public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<IdentityUser, IdentityRole>() // services.AddDefaultIdentity<IdentityUser>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddRazorPagesOptions(options => { options.AllowAreas = true; options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage"); options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout"); });
//这里设置了登陆路径,登出路径,没权限访问的路径 services.ConfigureApplicationCookie(options => { options.LoginPath = $"/Identity/Account/Login"; options.LogoutPath = $"/Identity/Account/Logout"; options.AccessDeniedPath = $"/Identity/Account/AccessDenied"; }); // using Microsoft.AspNetCore.Identity.UI.Services; 这里注册了一个IEmailSender邮件发送接口的实现 services.AddSingleton<IEmailSender, EmailSender>(); }
邮件实现的代码:
public class EmailSender : IEmailSender { public Task SendEmailAsync(string email, string subject, string message) { return Task.CompletedTask; } }
结束!
参考文档:
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2&tabs=visual-studio#scaffold-identity-into-an-mvc-project-without-existing-authorization