资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Nancy之Forms验证-创新互联

授权几乎是所以系统都不可或缺的部分,在Nancy中怎么授权呢?我们这篇博文来说一下Nancy的Forms授权。

三山ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!

首先在NuGet上安装Nancy.Authentication.Forms

Nancy之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;
        }
        /// 
        /// 实现接口的成员
        /// 
        public string UserName
        {
            get;
            set;
        }
 
        public string Password
        {
            get;
            set;
        }
 
        public string Role
        {
            get;
            set;
        }
        /// 
        /// 这个是Nancy授权中必须的
        /// 
        public Guid GUID
        {
            get;
            set;
        }
        /// 
        /// 实现接口的成员
        /// 
        public IEnumerable 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 _users;
        static UserMapper()
        {
            //初始化验用户数据
            _users = new List();
            _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" });
        }
        /// 
        /// 实现接口的成员,获取用户的角色,以便验证授权
        /// 
        /// 
        /// 
        /// 
        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 } };
        }
        /// 
        /// 验证用户,验证成功返回用户的GUID,这是规定
        /// 
        /// 
        /// 
        /// 
        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()//用户对应的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();
 
                 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



    
    Login
    
        body {
            text-align: center;
        }
    


    
        UserName:
        Password:
        
        @if (ViewBag["error"])
        {
            check username or password please
        }
    

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设置。

Nancy之Forms验证

如果用户名或密码错误 ,会得到提示:

Nancy之Forms验证

如果用户名密码正确:

Nancy之Forms验证

如果不具备权限的人(UserName:bbb,Passowrd:222222)登录,会报403错误(这个不太友下,下篇博客解决)

Nancy之Forms验证

这样就能轻量级的按解色来授权我们的系统了。

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


标题名称:Nancy之Forms验证-创新互联
分享路径:http://cdkjz.cn/article/dohdcd.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220