Use of the open-source framework of NancyFx 2.0-Authentication and nancy framework
Create an empty project
After creating an empty project, install the three packages through NuGet.
- Nancy
- Nancy. Hosting. Aspnet
- Nancy. ViewEnglines. Razor
Add the three folders Models, Module, and Views to the project, and add the UserModel class to Models.
public string Username { get; set; } public UserModel(string username) { this.Username = username; }
Add the MainModule class to the Module folder.
Get("/", Lexan => { return View["index.cshtml"]; }); Get("/login", Lexan => { return View["login.cshtml",this.Request.Query.returnUrl]; });
Then add the SecureModule class and the AnotherVerySecureModule class.
public SecureModule():base("/secure") { this.RequiresAuthentication(); Get("/",Lexan=> { var model = new UserModel(this.Context.CurrentUser.Identity.Name); return View["secure.cshtml",model]; }); }
public AnotherVerySecureModule():base("/superSecure") { this.RequiresClaims(Lexan=>Lexan.Type==ClaimTypes.Role&&Lexan.Value=="SuperSecure"); Get("/",Lexan=> { var model = new UserModel(this.Context.CurrentUser.Identity.Name); return View["superSecure.cshtml",model]; }); }
Add the AuthenticationBootstrapper class to the root directory
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); pipelines.BeforeRequest += ctx => { var username = ctx.Request.Query.username; if (username.HasValue) { ctx.CurrentUser = new ClaimsPrincipal(new ClaimsIdentity(BuildClaims(username), "querystring")); } return null; }; pipelines.AfterRequest += ctx => { if (ctx.Response.StatusCode==HttpStatusCode.Unauthorized) { ctx.Response = new RedirectResponse("/login?retutnUrl="+ Uri.EscapeDataString(ctx.Request.Path)); } }; } private static IEnumerable<Claim> BuildClaims(string userName) { var claims = new List<Claim>(); if (String.Equals(userName,"Lexan",StringComparison.OrdinalIgnoreCase)) { claims.Add(new Claim(ClaimTypes.Role,"SuperSecure")); } return claims; }
Add View index, login, secure, and superSecure in Views.
Then modify Web. config, as shown in figure
Run
Thank you!