一、前言

想必大家或多或少都听过微软推出的ASP.NET Identity技术,可以简单的认为就是一种授权的实现

很巧的是,Nancy中也有与之相类似的技术Authentication,这两者之间都用到了一些相通的安全技术

(我没有去看ASP.NET Identity的内部实现,是从它的简单用法中判断的)

正式开始介绍之前先推荐几篇ASP.NET Identity的好文章

r01cn 的 ASP.NET Identity系列教程(目录)

腾飞(Jesse) 的 MVC5 - ASP.NET Identity登录原理 - Claims-based认证和OWIN

好了,下面还是用demo的形式来介绍怎么简单使用Forms authentication吧

二、简单使用

1)、新建一个空的asp.net项目

2)、通过NuGet安装相应的包

       Install-Package Nancy
  Install-Package Nancy.Hosting.Aspnet
Install-Package Nancy.Authentication.Forms
Install-Package Dapper

由于用到了数据库访问,所以还安装了Dapper

3)、建立数据表

 CREATE TABLE [dbo].[SystemUser](
[SystemUserId] [uniqueidentifier] NOT NULL,
[SystemUserName] [nvarchar](50) NOT NULL,
[SystemUserPassword] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_SystemUser] PRIMARY KEY CLUSTERED
(
[SystemUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

同时像表中插入两条数据

 INSERT INTO [dbo].[SystemUser]([SystemUserId],[SystemUserName],[SystemUserPassword])
VALUES(newid(),'catcher','')
INSERT INTO [dbo].[SystemUser]([SystemUserId],[SystemUserName],[SystemUserPassword])
VALUES(newid(),'admin','')

注:由于是演示,所以密码没有进行加密处理

4)、建立相应的文件夹

Models用于存放模型

Modules用于存放相应的操作

Views用于存放视图

5)、编写模型 SystemUser.cs

     public class SystemUser
{
public Guid SystemUserId { get; set; }
public string SystemUserName { get; set; }
public string SystemUserPassword { get; set; }
}  

6)、编写HomeModule.cs

 using Dapper;
using Nancy;
using Nancy.Authentication.Forms;
using Nancy.ModelBinding;
using NancyDemoForFormsauthentication.Models;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace NancyDemoForFormsauthentication.Modules
{
public class HomeModule : NancyModule
{
public HomeModule()
{
Get["/"] = _ =>
{
return View["index"];
};
Get["/login"] = _ =>
{
return View["login"];
};
Post["/login"] = _ =>
{
var loginUser = this.Bind<SystemUser>();
SystemUser user = GetValidUser(loginUser.SystemUserName, loginUser.SystemUserPassword);
if (user == null)
{
return Response.AsText("出错了", "text/html;charset=UTF-8");
}
return this.LoginAndRedirect(user.SystemUserId, fallbackRedirectUrl: "/secure");
};
}
private readonly string sqlconnection =
"Data Source=127.0.0.1;Initial Catalog=NancyDemo;User Id=sa;Password=dream_time1314;";
private SqlConnection OpenConnection()
{
SqlConnection connection = new SqlConnection(sqlconnection);
connection.Open();
return connection;
}
private SystemUser GetValidUser(string name, string pwd)
{
using (IDbConnection conn = OpenConnection())
{
const string query = "select * from SystemUser where SystemUserName=@SystemUserName and SystemUserPassword=@SystemUserPassword";
return conn.Query<SystemUser>(query, new { SystemUserName = name, SystemUserPassword = pwd }).SingleOrDefault();
}
}
}
}

其中,登录的post方法中用到了 LoginAndRedirect 这个静态方法

这个方法位于ModuleExtensions.cs中,返回值是Response类型的

         public static Response LoginAndRedirect(this INancyModule module, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = "/")
{
return FormsAuthentication.UserLoggedInRedirectResponse(module.Context, userIdentifier, cookieExpiry, fallbackRedirectUrl);
}

看方法名都能知道这个是用来干什么的!

还有Response.AsText后面的第二个参数可以让中文不乱码!!

7)、编写相应的视图

index.html

 <!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h2>Nancy之基于Forms authentication的简单使用</h2>
<p>访问需要权限的页面</p>
<a href="/secure">secure</a>
</body>
</html>

login.html

 <!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form method="post" action="/login">
<label>姓名:</label><input type="text" name="SystemUserName" /><br />
<label>密码:</label><input type="password" name="SystemUserPassword" /><br />
<input type="submit" />
</form>
</body>
</html>
 

8)、编写SecureModule.cs

 using Nancy;
using Nancy.Security; namespace NancyDemoForFormsauthentication.Modules
{
public class SecureModule : NancyModule
{
public SecureModule()
{
this.RequiresAuthentication();
Get["/secure"] = _ =>
{
return "Hello ," + this.Context.CurrentUser.UserName;
};
}
}
}

其中

 this.RequiresAuthentication();

这句是关键!!表明需要验证才能通过。位于Nancy.Security这个命名空间

通过验证访问后会打印出当前的用户名称。

9)、编写Bootstraper.cs

 using Nancy;
using Nancy.Authentication.Forms;
using Nancy.TinyIoc;
using Nancy.Bootstrapper;
namespace NancyDemoForFormsauthentication
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
{
base.ConfigureRequestContainer(container, context);
container.Register<IUserMapper, UserMapper>();
}
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>(),
};
FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
}
}
}

这里是至关重要的一步!!!

要在RequestStartup中启用我们的FormsAuthentication!!

同时我们还要配置FormsAuthenticationConfiguration

注册了UserMapper,所以我们接下来就是实现UserMapper

10)、编写UserMapper.cs

 using Dapper;
using Nancy;
using Nancy.Authentication.Forms;
using Nancy.Security;
using NancyDemoForFormsauthentication.Models;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace NancyDemoForFormsauthentication
{
public class UserMapper : IUserMapper
{
public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
{
using (IDbConnection conn = OpenConnection())
{
const string query = "select * from SystemUser where SystemUserId=@SystemUserId";
var user = conn.Query<SystemUser>(query, new { SystemUserId = identifier }).SingleOrDefault();
if (user == null)
{
return null;
}
else
{
return new UserIdentity
{
UserName = user.SystemUserName,
Claims = new[] { "SystemUser"}
};
}
}
}
private readonly string sqlconnection =
"Data Source=127.0.0.1;Initial Catalog=NancyDemo;User Id=sa;Password=dream_time1314;";
private SqlConnection OpenConnection()
{
SqlConnection connection = new SqlConnection(sqlconnection);
connection.Open();
return connection;
}
}
}

UserMapper必须要实现IUserMapper这个接口!同时返回一个实现IUserIdentity接口的对象。

11)、编写UserIdentity.cs

 using Nancy.Security;
using System.Collections.Generic;
namespace NancyDemoForFormsauthentication
{
public class UserIdentity : IUserIdentity
{
public string UserName { get; set; }
public IEnumerable<string> Claims { get; set; }
}
}

到这里所有的工作都已经做完了,下面就是看看效果了

我们点击 secure链接,发现自动跳转到登录界面了!!

我们输入用户名和密码

登录成功,并返回到secure页面了!

当我们输入错误的用户名和密码时

最后是本次示例代码:

https://github.com/hwqdt/Demos/tree/master/src/NancyDemoForFormsauthentication

Nancy之Forms authentication的简单使用的更多相关文章

  1. Nancy 学习-身份认证(Forms authentication) 继续跨平台

    开源 示例代码:https://github.com/linezero/NancyDemo 上篇讲解Nancy的Basic Authentication,现在来学习Nancy 的Forms身份认证. ...

  2. ASP.NET 4.0 forms authentication issues with IE11

    As I mentioned earlier, solutions that rely on User-Agent sniffing may break, when a new browser or ...

  3. Forms Authentication in ASP.NET MVC 4

    原文:Forms Authentication in ASP.NET MVC 4 Contents: Introduction Implement a custom membership provid ...

  4. Forms Authentication and Role based Authorization: A Quicker, Simpler, and Correct Approach

    https://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization Problem ...

  5. An Overview of Forms Authentication (C#)

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/introduction/an-o ...

  6. .net core 共享 .Net Forms Authentication cookie

    Asp.net 项目迁移到 asp.net core 项目后需要 兼容以前老的项目的登录方式. Forms Authentication cookie 登录. 从网上搜集到关于这个问题的解决思路都没有 ...

  7. ASP.NET Session and Forms Authentication and Session Fixation

    https://peterwong.net/blog/asp-net-session-and-forms-authentication/ The title can be misleading, be ...

  8. Forms authentication timeout vs sessionState timeout

    https://stackoverflow.com/questions/17812994/forms-authentication-timeout-vs-sessionstate-timeout Th ...

  9. SSRS 2016 Forms Authentication

    SSRS 2016 comes with completely new report manager web interface and implementing form authenticatio ...

随机推荐

  1. ORA-01861: 文字与格式字符串不匹配

    问题:插入数据不成功 解决:借口实现类里面的sql语句带值放到数据库中运行,如果不成功是sql语句的错误.

  2. Lesson 3 Please send me a card

    Text Postcards always spoil my holidays. Last summer, I went to Italy. I visited museums and sat in ...

  3. Backbone源码分析(二)

    在传统MVC框架模式中,Model承担业务逻辑的任务.Backbone作为一个mvc框架,主要的业务逻辑交由Model与Collection来实现.Model代表领域对象,今天主要学一下Model源码 ...

  4. Python黑帽编程 3.1 ARP欺骗

    Python灰帽编程 3.1 ARP欺骗 ARP欺骗是一种在局域网中常用的攻击手段,目的是让局域网中指定的(或全部)的目标机器的数据包都通过攻击者主机进行转发,是实现中间人攻击的常用手段,从而实现数据 ...

  5. HappyAA服务器部署笔记1(nginx+tomcat的安装与配置)

    这是本人的服务器部署笔记.文章名称叫"部署笔记1"的原因是之后我对这个进行了改进之后,会有"部署笔记2","部署笔记3"...循序渐进,估计 ...

  6. [.net 面向对象程序设计进阶] (27) 团队开发利器(六)分布式版本控制系统Git——在Visual Studio 2015中使用Git

    [.net 面向对象程序设计进阶] (26) 团队开发利器(六)分布式版本控制系统Git——在Visual Studio 2015中使用Git 本篇导读: 接上两篇,继续Git之旅 分布式版本控制系统 ...

  7. 玩转Windows服务系列——服务运行、停止流程浅析

    通过研究Windows服务注册卸载的原理,感觉它并没有什么特别复杂的东西,Windows服务正在一步步退去它那神秘的面纱,至于是不是美女,大家可要睁大眼睛看清楚了. 接下来研究一下Windows服务的 ...

  8. 防刷票机制研究和.NET HttpRequest Proxy

    最近应朋友之约 测试他做的投票网站 防刷票机制能力如何,下面有一些心得和体会. 朋友网站用PHP写的,走的是HttpRequest,他一开始认为IP认证应该就差不多了.但说实话这种很low,手动更换代 ...

  9. CSS3 Animation制作飘动的浮云和星星效果

    带平行视差效果的星星 先看效果: 如果下方未出现效果也可前往这里查看 http://sandbox.runjs.cn/show/0lz3sl9y 下面我们利用CSS3的animation写出这样的动画 ...

  10. 如何用TDR来测试PCB板的线路阻抗

    隔壁小王已经讲了TDR的原理以及如何确定TDR的分辨率.那么,我们要正确测量PCB板上的线路阻抗,还有哪些需要注意的地方呢? 1. 阻抗测试的行业标准 之前贴过好多张阻抗测试的图片,重新再贴一张给大家 ...