1. 程式人生 > >ASP.NET Core Authentication and Authorization

ASP.NET Core Authentication and Authorization

最近把一個Asp .net core 2.0的專案遷移到Asp .net core 3.1,專案啟動的時候直接報錯: ``` InvalidOperationException: Endpoint CoreAuthorization.Controllers.HomeController.Index (CoreAuthorization) contains authorization metadata, but a middleware was not found that supports authorization. Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...). Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAuthMiddlewareException(Endpoint endpoint) ``` 看意思是缺少了一個authorization的中介軟體,這個專案在Asp.net core 2.0上是沒問題的。 startup是這樣註冊的: ``` public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => { options.LoginPath = "/account/Login"; }); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } ``` 查了文件後發現3.0的示例程式碼多了一個UseAuthorization,改成這樣就可以了: ``` app.UseRouting(); app.UseAuthentication(); //use授權中介軟體 app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); ``` 看來Asp .net Core 3.1的認證跟授權又不太一樣了,只能繼續看文件學習了。 ## UseAuthentication and UseAuthorization 先說一下Authentication跟Authorization的區別。這兩個單詞長的十分相似,而且還經常一起出現,很多時候容易搞混了。 1. Authentication是認證,明確是你誰,確認是不是合法使用者。常用的認證方式有使用者名稱密碼認證。 2. Authorization是授權,明確你是否有某個許可權。當用戶需要使用某個功能的時候,系統需要校驗使用者是否需要這個功能的許可權。 所以這兩個單詞是不同的概念,不同層次的東西。UseAuthorization在asp.net core 2.0中是沒有的。在3.0之後微軟明確的把授權功能提取到了Authorization中介軟體裡,所以我們需要在UseAuthentication之後再次UseAuthorization。否則,當你使用授權功能比如使用[Authorize]屬性的時候系統就會報錯。 ## Authentication(認證) 認證的方案有很多,最常用的就是使用者名稱密碼認證,下面演示下基於使用者名稱密碼的認證。新建一個MVC專案,新增AccountController: ``` [HttpPost] public async Task