對於沒有包含認證(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