您好,登錄后才能下訂單哦!
授權幾乎是所以系統都不可或缺的部分,在Nancy中怎么授權呢?我們這篇博文來說一下Nancy的Forms授權。
首先在NuGet上安裝Nancy.Authentication.Forms
Nancy的Forms驗證得實現IUserMapper接口,用戶類實現IUserIdentity接口(為了方便,我把DB的User,Model的User全合成一個User)
User.cs
using Nancy.Security; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestSelfHostWeb { public class User : IUserIdentity { public User() { } public User(string userName) { UserName = userName; } /// <summary> /// 實現接口的成員 /// </summary> public string UserName { get; set; } public string Password { get; set; } public string Role { get; set; } /// <summary> /// 這個是Nancy授權中必須的 /// </summary> public Guid GUID { get; set; } /// <summary> /// 實現接口的成員 /// </summary> public IEnumerable<string> Claims { get; set; } } }
UserMapper.cs
using Nancy.Authentication.Forms; using System; using System.Collections.Generic; using System.Linq; using Nancy; using Nancy.Security; namespace TestSelfHostWeb { class UserMapper : IUserMapper { //這個用戶集合可以來自數據庫 static List<User> _users; static UserMapper() { //初始化驗用戶數據 _users = new List<User>(); _users.Add(new User() { UserName = "aaa", Password = "111111", GUID = new Guid("33e67c06-ed6e-4bd7-a5b0-60ee0fea890c"), Role = "admin" }); _users.Add(new User() { UserName = "bbb", Password = "222222", GUID = new Guid("fba4be7d-25af-416e-a641-a33174f435d1"), Role = "user" }); } /// <summary> /// 實現接口的成員,獲取用戶的角色,以便驗證授權 /// </summary> /// <param name="identifier"></param> /// <param name="context"></param> /// <returns></returns> public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context) { var user = _users.FirstOrDefault(u => u.GUID == identifier); return user == null ? null : new User(user.UserName) { Claims = new string[] { user.Role } }; } /// <summary> /// 驗證用戶,驗證成功返回用戶的GUID,這是規定 /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static Guid? ValidateUser(string userName, string password) { var user = _users.FirstOrDefault(u => u.UserName == userName && u.Password == password); if (user == null) { return null; } return user.GUID; } } }
Bootstrapper.cs
using Nancy; using Nancy.Bootstrapper; using Nancy.TinyIoc; using Nancy.Authentication.Forms; namespace TestSelfHostWeb { public class Bootstrapper : DefaultNancyBootstrapper { protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); //驗證配置文件 var formsAuthConfiguration = new FormsAuthenticationConfiguration() { RedirectUrl = "~/login",//無驗證跳轉的路由 UserMapper = container.Resolve<IUserMapper>()//用戶對應的Mapper }; //開啟驗證 FormsAuthentication.Enable(pipelines, formsAuthConfiguration); } } }
Login.cs
using Nancy; using Nancy.Authentication.Forms; using Nancy.ModelBinding; using System; namespace TestSelfHostWeb.Modules { public class LoginModule : NancyModule { public LoginModule() { Get["/login"] = parameters => { //用戶名和密碼驗證失敗的標識 ViewBag["error"] = Request.Query.error; return View["login"]; }; Post["/login"] = parameters => { var user = this.Bind<User>(); var guid= UserMapper.ValidateUser(user.UserName, user.Password); if (guid == null) { //按用戶名密碼查詢不到時作的標識 return this.LogoutAndRedirect("~/login?error=true"); } DateTime? expiry = null; //登錄后跳轉頁面,必需用戶的GUID return this.LoginAndRedirect(guid.Value, expiry); }; } } }
login.cshtml
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<TestSelfHostWeb.User> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Login</title> <style type="text/css"> body { text-align: center; } </style> </head> <body> <form action="\Login" method="post"> UserName:<input id="UserName" name="UserName" type="text" /> Password:<input id="Password" name="Password" type="password" /> <input type="submit" value="Login" /> @if (ViewBag["error"]) { <font color="red">check username or password please</font> } </form> </body> </html>
Index.cs
using Nancy; using Nancy.Security; namespace TestSelfHostWeb.Modules { public class IndexModule : NancyModule { public IndexModule() { //開啟全局驗證 this.RequiresAuthentication(); Get["/"] = parameters => { //開啟角色驗證,只有該角色可以訪問本路由 this.RequiresClaims("admin"); return View["index"]; }; } } }
Index.cshtml同上篇的indexx.cshtml
到了test的時刻了
啟動host(注意以管理員身份運行)
訪問網站的主頁,如下圖,會跳轉到登記頁,這是因為index.cs的IndexModule中開啟了this.RequiresAuthentication()驗證,為什么會跳轉到login路由中呢,是因為Bootstrapper中formAuthConfiguration中的RedirectUrl設置。
如果用戶名或密碼錯誤 ,會得到提示:
如果用戶名密碼正確:
如果不具備權限的人(UserName:bbb,Passowrd:222222)登錄,會報403錯誤(這個不太友下,下篇博客解決)
這樣就能輕量級的按解色來授權我們的系統了。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。