1. 程式人生 > >NancyFx 2.0的開源框架的使用-Authentication

NancyFx 2.0的開源框架的使用-Authentication

web src query msi containe override 項目 img 9.png

新建一個空的項目

技術分享

技術分享

新建好了空的項目以後,接著通過NuGet安裝一下三個包

  • Nancy
  • Nancy.Hosting.Aspnet
  • Nancy.ViewEnglines.Razor

技術分享

然後在項目中添加Models,Module,Views三個文件夾,並在Models中添加UserModel類

        public string  Username { get; set; }
        public UserModel(string username)
        {
            this.Username = username;
        }

技術分享

然後往Module文件夾裏面添加MainModule類

 Get("/", Lexan => { return View["index.cshtml"]; });
            Get("/login", Lexan => { return View["login.cshtml",this.Request.Query.returnUrl]; });

技術分享

再繼續添加SecureModule類,AnotherVerySecureModule類

        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]; }); }

技術分享

根目錄添加AuthenticationBootstrapper類

        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;
        }

技術分享

繼續在Views裏添加視圖index,login,secure,superSecure

技術分享

技術分享

技術分享

技術分享

再然後修改一下Web.config如下圖

技術分享

運行如下圖

技術分享

技術分享

技術分享

謝謝觀看!

NancyFx 2.0的開源框架的使用-Authentication