開源 示例代碼:https://github.com/linezero/NancyDemo
前面講解Nancy的進階部分,現在來學習Nancy 的身份認證。
本篇主要講解Basic Authentication ,基本認證。
在HTTP中,基本認證是一種用來允許Web瀏覽器或其他客戶端程序在請求時提供用戶名和口令形式的身份憑證的一種登錄驗證方式。
說明:本篇示例是基於 Nancy 1.4.3。Nancy 2.0預覽版 已經發布,版本改動較大,故特此說明。
准備
安裝 Nancy.Authentication.Basic
Install-Package Nancy.Authentication.Basic -Version 1.4.1
我這里就不新建項目了,直接在之前的項目中進行添加。
1.實現IUserValidator 接口
新建一個類,實現IUserValidator接口。
public class BasicUserValidator:IUserValidator { public IUserIdentity Validate(string username, string password) { if (username == "linezero" && password == "demo") { return new BasicUser() { UserName = username }; } return null; } }
這里我將用戶判斷固定了,大家也可以自己使用各種方式去判斷。
2.實現IUserIdentity 接口
public class BasicUser : IUserIdentity { public string UserName { get; set; } public IEnumerable<string> Claims { get; set; } }
3.在Nancy管道中添加認證
在繼承 DefaultNancyBootstrapper 的 Bootstrapper 中的 ApplicationStartup 添加如下代碼:
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration( container.Resolve<IUserValidator>(), "MyRealm"));//Basic認證添加 pipelines.OnError += Error; }
主要代碼:
pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration( container.Resolve<IUserValidator>(), "MyRealm"));
添加好以后,啟動程序。
訪問:http://localhost:9000
輸入linezero demo 成功認證。
4. 獲取授權用戶
我們要在module 中獲取授權用戶使用 Context.CurrentUser 就可以獲取到用戶信息。
在HomeModule 中添加一個獲取用戶名:
Context.CurrentUser.UserName
實現如下:
5.跨平台
將程序上傳至linux執行,訪問 對應地址:
示例代碼下載:https://github.com/linezero/NancyDemo
示例代碼包含之前示例,並且會持續更新,歡迎大家Star。
如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。