asp.net core 基本身份驗證
阿新 • • 發佈:2020-08-27
1.建立專案
- 使用visual studio建立一個空的asp.net core mvc專案
- 在StartUp類中新增程式碼
//服務註冊中
services.AddControllersWithViews();
//管道中
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
- 新建一個HomeController,並建立三個方法和檢視
//無需驗證許可權的方法 public IActionResult Index() { return View(); } //需要驗證許可權的方法 [Authorize] public IActionResult Secret() { return View(); } public IActionResult Authenticate() { return RedirectToAction("Index"); }
- 此時我們訪問/home/index可以看到正確的頁面,訪問/home/secret會報一個錯誤:
InvalidOperationException: Endpoint Basic.Controllers.HomeController.Secret (Basic) 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(...).
這個錯誤的原因是我們沒有配置鑑權,框架不知道如何處理驗證的問題
2.配置基於cookie的驗證
基於以上的程式碼,我們做如下修改:
- 在服務配置方法中:
services.AddAuthentication("CookieAuth") .AddCookie("CookieAuth", config => { config.Cookie.Name = "mysite.cookie"; #生成的cookie名稱 config.LoginPath = "/Home/Authenticate"; #登入地址,如果沒有配置,預設會跳轉/Account/Login });
- 在管道配置方法中:
//who are you?
app.UseAuthentication(); # 認證中介軟體,必須位於 app.UseRouting() 和 app.UseEndpoints() 之間
//are you allowed?
app.UseAuthorization(); # 授權中介軟體,必須位於 app.UseRouting() 和 app.UseEndpoints() 之間,必須位於 app.UseAuthentication() 下面
- 在認證方法 Home/Authenticate 中寫入如下程式碼:
//在此可以進行一些資料庫驗證,然後取出資訊放入下面
//定義一些身份資訊,可以定義多個
var myClaims = new List<Claim>()
{
new Claim(ClaimTypes.Name,"zhangsan"),
new Claim(ClaimTypes.Email,"[email protected]"),
new Claim("zhangsan.hobby","shopping")
};
var otherClaims = new List<Claim>()
{
new Claim(ClaimTypes.Name,"zhangsan"),
new Claim(ClaimTypes.Email,"[email protected]"),
new Claim("zhangsan.hobby","shopping")
};
var myIdentity = new ClaimsIdentity(myClaims, "myIdentity");
var otherIdentity = new ClaimsIdentity(otherClaims, "otherIdentity");
var userPrinciple = new ClaimsPrincipal(new []{myIdentity,otherIdentity});
//呼叫框架登入方法
HttpContext.SignInAsync(userPrinciple);
return RedirectToAction("Index");
- 再次執行專案,訪問 /home/secret 頁面,會發現瀏覽器的cookie已經生成,第一次會跳轉到 /home/index,第二次再訪問就可以看到 /home/secret 頁面的內容了
3.完整程式碼
- Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("CookieAuth")
.AddCookie("CookieAuth", config =>
{
config.Cookie.Name = "mysite.cookie";
config.LoginPath = "/Home/Authenticate";
});
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
//who are you?
app.UseAuthentication();
//are you allowed?
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
- HomeController.cs
public class HomeController:Controller
{
public IActionResult Index()
{
return View();
}
[Authorize]
public IActionResult Secret()
{
return View();
}
public IActionResult Authenticate()
{
//在此可以進行一些資料庫驗證,然後取出資訊放入下面
//定義一些身份資訊,可以定義多個
var myClaims = new List<Claim>()
{
new Claim(ClaimTypes.Name,"zhangsan"),
new Claim(ClaimTypes.Email,"[email protected]"),
new Claim("zhangsan.hobby","shopping")
};
var otherClaims = new List<Claim>()
{
new Claim(ClaimTypes.Name,"zhangsan"),
new Claim(ClaimTypes.Email,"[email protected]"),
new Claim("zhangsan.hobby","shopping")
};
var myIdentity = new ClaimsIdentity(myClaims, "myIdentity");
var otherIdentity = new ClaimsIdentity(otherClaims, "otherIdentity");
var userPrinciple = new ClaimsPrincipal(new []{myIdentity,otherIdentity});
//呼叫框架登入方法
HttpContext.SignInAsync(userPrinciple);
return RedirectToAction("Index");
}
}