一、前言
想必大家或多或少都听过微软推出的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安装相应的包
1 Install-Package Nancy2 Install-Package Nancy.Hosting.Aspnet3 Install-Package Nancy.Authentication.Forms4 Install-Package Dapper
由于用到了数据库访问,所以还安装了Dapper
3)、建立数据表
1 CREATE TABLE [dbo].[SystemUser]( 2 [SystemUserId] [uniqueidentifier] NOT NULL, 3 [SystemUserName] [nvarchar](50) NOT NULL, 4 [SystemUserPassword] [nvarchar](50) NOT NULL, 5 CONSTRAINT [PK_SystemUser] PRIMARY KEY CLUSTERED 6 ( 7 [SystemUserId] ASC 8 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 9 ) ON [PRIMARY]10 GO
同时像表中插入两条数据
1 INSERT INTO [dbo].[SystemUser]([SystemUserId],[SystemUserName],[SystemUserPassword])2 VALUES(newid(),'catcher','123')3 INSERT INTO [dbo].[SystemUser]([SystemUserId],[SystemUserName],[SystemUserPassword])4 VALUES(newid(),'admin','123')
注:由于是演示,所以密码没有进行加密处理
4)、建立相应的文件夹
Models用于存放模型
Modules用于存放相应的操作
Views用于存放视图
5)、编写模型 SystemUser.cs
1 public class SystemUser2 {3 public Guid SystemUserId { get; set; }4 public string SystemUserName { get; set; }5 public string SystemUserPassword { get; set; }6 }
6)、编写HomeModule.cs
1 using Dapper; 2 using Nancy; 3 using Nancy.Authentication.Forms; 4 using Nancy.ModelBinding; 5 using NancyDemoForFormsauthentication.Models; 6 using System.Data; 7 using System.Data.SqlClient; 8 using System.Linq; 9 namespace NancyDemoForFormsauthentication.Modules10 {11 public class HomeModule : NancyModule12 {13 public HomeModule()14 {15 Get["/"] = _ =>16 {17 return View["index"];18 };19 Get["/login"] = _ =>20 {21 return View["login"];22 };23 Post["/login"] = _ =>24 {25 var loginUser = this.Bind<SystemUser>();26 SystemUser user = GetValidUser(loginUser.SystemUserName, loginUser.SystemUserPassword);27 if (user == null)28 {29 return Response.AsText("出错了", "text/html;charset=UTF-8");30 }31 return this.LoginAndRedirect(user.SystemUserId, fallbackRedirectUrl: "/secure");32 };33 }34 private readonly string sqlconnection =35 "Data Source=127.0.0.1;Initial Catalog=NancyDemo;User Id=sa;Password=dream_time1314;";36 private SqlConnection OpenConnection()37 {38 SqlConnection connection = new SqlConnection(sqlconnection);39 connection.Open();40 return connection;41 }42 private SystemUser GetValidUser(string name, string pwd)43 {44 using (IDbConnection conn = OpenConnection())45 {46 const string query = "select * from SystemUser where SystemUserName=@SystemUserName and SystemUserPassword=@SystemUserPassword";47 return conn.Query<SystemUser>(query, new { SystemUserName = name, SystemUserPassword = pwd }).SingleOrDefault();48 }49 }50 }51 }
其中,登录的post方法中用到了 LoginAndRedirect 这个静态方法
这个方法位于ModuleExtensions.cs中,返回值是Response类型的
1 public static Response LoginAndRedirect(this INancyModule module, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = "/")2 {3 return FormsAuthentication.UserLoggedInRedirectResponse(module.Context, userIdentifier, cookieExpiry, fallbackRedirectUrl);4 }
看方法名都能知道这个是用来干什么的!
还有Response.AsText后面的第二个参数可以让中文不乱码!!
7)、编写相应的视图
index.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <meta charset="utf-8" /> 6 </head> 7 <body> 8 <h2 id="Nancy之基于Forms-authentication的简单使用">Nancy之基于Forms authentication的简单使用</h2> 9 <p>访问需要权限的页面</p>10 <a href="/secure">secure</a>11 </body>12 </html>
login.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <meta charset="utf-8" /> 6 </head> 7 <body> 8 <form method="post" action="/login"> 9 <label>姓名:</label><input type="text" name="SystemUserName" /><br />10 <label>密码:</label><input type="password" name="SystemUserPassword" /><br />11 <input type="submit" />12 </form>13 </body>14 </html>
8)、编写SecureModule.cs
1 using Nancy; 2 using Nancy.Security; 3 4 namespace NancyDemoForFormsauthentication.Modules 5 { 6 public class SecureModule : NancyModule 7 { 8 public SecureModule() 9 {10 this.RequiresAuthentication();11 Get["/secure"] = _ =>12 {13 return "Hello ," + this.Context.CurrentUser.UserName;14 };15 }16 }17 }
其中
1 this.RequiresAuthentication();
这句是关键!!表明需要验证才能通过。位于Nancy.Security这个命名空间
通过验证访问后会打印出当前的用户名称。
9)、编写Bootstraper.cs
1 using Nancy; 2 using Nancy.Authentication.Forms; 3 using Nancy.TinyIoc; 4 using Nancy.Bootstrapper; 5 namespace NancyDemoForFormsauthentication 6 { 7 public class Bootstrapper : DefaultNancyBootstrapper 8 { 9 protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)10 {11 base.ConfigureRequestContainer(container, context);12 container.Register<IUserMapper, UserMapper>();13 }14 protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)15 {16 base.RequestStartup(container, pipelines, context);17 var formsAuthConfiguration = new FormsAuthenticationConfiguration18 {19 RedirectUrl = "~/login",20 UserMapper = container.Resolve<IUserMapper>(),21 };22 FormsAuthentication.Enable(pipelines, formsAuthConfiguration);23 }24 }25 }
这里是至关重要的一步!!!
要在RequestStartup中启用我们的FormsAuthentication!!
同时我们还要配置FormsAuthenticationConfiguration
注册了UserMapper,所以我们接下来就是实现UserMapper
10)、编写UserMapper.cs
1 using Dapper; 2 using Nancy; 3 using Nancy.Authentication.Forms; 4 using Nancy.Security; 5 using NancyDemoForFormsauthentication.Models; 6 using System; 7 using System.Data; 8 using System.Data.SqlClient; 9 using System.Linq;10 namespace NancyDemoForFormsauthentication11 {12 public class UserMapper : IUserMapper13 {14 public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)15 {16 using (IDbConnection conn = OpenConnection())17 {18 const string query = "select * from SystemUser where SystemUserId=@SystemUserId";19 var user = conn.Query<SystemUser>(query, new { SystemUserId = identifier }).SingleOrDefault();20 if (user == null)21 {22 return null;23 }24 else25 {26 return new UserIdentity27 {28 UserName = user.SystemUserName,29 Claims = new[] { "SystemUser"}30 };31 }32 }33 }34 private readonly string sqlconnection =35 "Data Source=127.0.0.1;Initial Catalog=NancyDemo;User Id=sa;Password=dream_time1314;";36 private SqlConnection OpenConnection()37 {38 SqlConnection connection = new SqlConnection(sqlconnection);39 connection.Open();40 return connection;41 }42 }43 }
UserMapper必须要实现IUserMapper这个接口!同时返回一个实现IUserIdentity接口的对象。
11)、编写UserIdentity.cs
1 using Nancy.Security; 2 using System.Collections.Generic; 3 namespace NancyDemoForFormsauthentication 4 { 5 public class UserIdentity : IUserIdentity 6 { 7 public string UserName { get; set; } 8 public IEnumerable<string> Claims { get; set; } 9 }10 }
到这里所有的工作都已经做完了,下面就是看看效果了
我们点击 secure链接,发现自动跳转到登录界面了!!
我们输入用户名和密码
登录成功,并返回到secure页面了!
当我们输入错误的用户名和密码时
最后是本次示例代码:
https://github.com/hwqdt/Demos/tree/master/src/NancyDemoForFormsauthentication

HTML의 핵심 목적은 브라우저가 웹 컨텐츠를 이해하고 표시 할 수 있도록하는 것입니다. 1. HTML은 TO 등과 같은 태그를 통해 웹 페이지 구조와 컨텐츠를 정의합니다. 2. HTML5는 멀티미디어 지원을 향상시키고 소개 및 태그를 향상시킵니다. 3.html은 사용자 상호 작용을 지원하기위한 양식 요소를 제공합니다. 4. HTML 코드를 최적화하면 HTTP 요청 감소 및 HTML 압축과 같은 웹 페이지 성능이 향상 될 수 있습니다.

htmltagsareessentialforwebdevelopmentasthuctureandenhancewebpages.1) thefinelayout, semantics 및 internactivity.2) semantictagsimproveAccessibility 및 sseo.3) appleasoftagscanoptimizeperformanceandenseRocRossercompatiber.

일관된 HTML 인코딩 스타일은 코드의 가독성, 유지 가능성 및 효율성을 향상시키기 때문에 중요합니다. 1) 소문자 태그 및 속성 사용, 2) 일관된 압입 유지, 3) 단일 또는 이중 인용문을 선택하고 고수하십시오. 4) 프로젝트에서 다양한 스타일을 혼합하지 않으십시오.

솔루션 Bootstrap4에서 다중 프로 젝트 회전 목마를 구현하는 것은 부트 스트랩 4에서 멀티 프로 젝트 회전 목마를 구현하는 것은 쉬운 일이 아닙니다. 부트 스트랩 ...

마우스 스크롤링 이벤트 침투의 효과를 달성하는 방법은 무엇입니까? 웹을 탐색하면 종종 특별한 상호 작용 디자인이 발생합니다. 예를 들어, DeepSeek 공식 웹 사이트에서 � ...

HTML 비디오의 기본 재생 제어 스타일은 CSS를 통해 직접 수정할 수 없습니다. 1. JavaScript를 사용하여 사용자 정의 컨트롤을 만듭니다. 2. CSS를 통해 이러한 통제를 아름답게합니다. 3. video.js 또는 plyr와 같은 라이브러리를 사용하여 호환성, 사용자 경험 및 성능을 고려하면 프로세스를 단순화 할 수 있습니다.

휴대 전화에서 기본 선택을 사용하는 데있어 잠재적 인 문제는 모바일 애플리케이션을 개발할 때 종종 상자를 선택해야 할 필요가 있습니다. 일반적으로 개발자 ...

휴대 전화에서 기본 선택을 사용하는 단점은 무엇입니까? 모바일 장치에서 애플리케이션을 개발할 때는 올바른 UI 구성 요소를 선택하는 것이 매우 중요합니다. 많은 개발자 ...


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

드림위버 CS6
시각적 웹 개발 도구
