NancyFx 2.0的开源框架的使用-Stateless
同样和前面一样新建一个空的Web项目,都在根目录添加Module,Models,Views文件夹

添加Nuget包

在Models文件夹里面添加UserModel类
public string Username { get; set; }
public UserModel(string username)
{
Username = username;
}

在Models文件夹里面添加Userdatabase类
static readonly List<Tuple<string, string>> ActiveApiKeys = new List<Tuple<string, string>>();
private static readonly List<Tuple<string, string>> User = new List<Tuple<string, string>>();
static UserDatabase()
{
User.Add(new Tuple<string, string>("Lexan","password"));
User.Add(new Tuple<string, string>("User","password"));
}
public static ClaimsPrincipal GetUserFromApiKey(string apiKey)
{
var activeKey = ActiveApiKeys.FirstOrDefault(x=>x.Item2==apiKey);
if (activeKey==null)
{
return null;
}
var userRecord = User.First(x=>x.Item1==activeKey.Item1);
return new ClaimsPrincipal(new GenericIdentity(userRecord.Item1,"Lexan"));
}
public static string ValidateUser(string username,string password)
{
//尝试从 "数据库" 中获取与给定用户名和密码匹配的用户
var userRecord = User.FirstOrDefault(x=>x.Item1==username&&x.Item2==password);
if (userRecord==null)
{
return null;
}
//既然用户已被验证, 请创建一个可用于后续请求的 api 密钥。
var apiKey = Guid.NewGuid().ToString();
ActiveApiKeys.Add(new Tuple<string, string>(username,apiKey));
return apiKey;
}
public static void RemoveApiKey(string apiKey)
{
var apiKeyToRemove = ActiveApiKeys.First(x=>x.Item2==apiKey);
ActiveApiKeys.Remove(apiKeyToRemove);
}
public static Tuple<string, string> CreateUser(string username, string password)
{
var user = new Tuple<string, string>(username,password);
User.Add(user);
return user;
}

在Module文件夹中添加AuthModule类,如下代码
public class AuthModule:NancyModule
{
//post ["/login"] 方法主要用于获取后续调用的 api 密钥
public AuthModule():base("/auth/")
{
Post("/", Lexan =>
{
var apiKey = UserDatabase.ValidateUser((string) this.Request.Form.Username,
(string)this.Request.Form.Password);
return string.IsNullOrEmpty(apiKey) ? new Response { StatusCode = HttpStatusCode.Unauthorized }
: this.Response.AsJson(new { ApiKey=apiKey});
});
//销毁关键api 密钥
Delete("/",Lexan=>
{
var apiKey = (string)this.Request.Form.ApiKey;
UserDatabase.RemoveApiKey(apiKey);
return new Response { StatusCode=HttpStatusCode.OK};
});
}

在Module文件下添加RootModule类
public RootModule()
{
Get("/",Lexan=>this.Response.AsText(
"这是一个 rest api,它是在另一个 vs 项目" +
"演示一个普通的 rest api 在" +
"从其他网站或应用程序访问它" +
"了解网站如何访问此 api, 运行" +
"Stateless.Web项目"+
"和构建Web同一项目中"
));
}

在Module文件夹下添加SecureModule类
public SecureModule()
{
Get("secure",Lexan=>
{
var identity = this.Context.CurrentUser;
var userModel = new UserModel(identity.Identity.Name);
return this.Response.AsJson(
new {
SecureContent= "下面是一些安全的内容, 只能看到你提供了正确的 apikey",
User=userModel
});
});
Post("/secure/creat_user",Lexan=>
{
Tuple<string, string> user = UserDatabase.CreateUser(this.Context.Request.Form["username"],
this.Context.Request.Form["password"]);
return this.Response.AsJson(new { username=user.Item1});
});
}

继续在根目录添加StatelessBootstrapper
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
{
//在请求启动时, 我们修改请求管线
//包括无状态身份验证
//配置无状态身份验证很简单。只需使用
//NancyContext 得到 apiKey。然后, 使用 apiKey 获取
//用户的身份。
//// base.RequestStartup(container, pipelines, context);
var configuration = new StatelessAuthenticationConfiguration(nancyContext =>
{
var apiKey = (string)nancyContext.Request.Query.ApiKey.Value;
return UserDatabase.GetUserFromApiKey(apiKey);
});
AllowAccessToConsumingSite(pipelines);
StatelessAuthentication.Enable(pipelines,configuration);
}
static void AllowAccessToConsumingSite(IPipelines pipelines)
{
pipelines.AfterRequest.AddItemToEndOfPipeline(x =>
{
x.Response.Headers.Add("访问-控制-允许-起源", "*");
x.Response.Headers.Add("访问-控制允许-方法", "开机自检、获取、删除、放入、选项");
});
}

再来看看运行的结果

成功了,谢谢欣赏!
NancyFx 2.0的开源框架的使用-Stateless的更多相关文章
- NancyFx 2.0的开源框架的使用-Stateless(二)
继续上一篇Stateless的博文,在上一篇的博文的基础上稍微加点东西 接下来右键解决方案添加新项目,一样建一个空的Web项目 然后在StatelessDemoWeb项目里面添加Views文件夹,Sc ...
- NancyFx 2.0的开源框架的使用-Basic
这是NancyFx开源框架中的Basic认证,学习一下! 首先当然是新建一个空的Web,BasicDemo 继续在项目中添加Nuget包,记得安装的Nuget包是最新的预发行版 Nancy Nancy ...
- NancyFx 2.0的开源框架的使用-CustomModule(自定义模块)
NancyFx框架的自定义模块 新建一个空的Web项目 然后通过NuGet库安装下面的包 Nancy Nancy.Hosting.Aspnet 然后添加Models,Module,Views三个文件夹 ...
- NancyFx 2.0的开源框架的使用-ModelBinding(实现绑定)
NancyFx框架中使用绑定模型 新建一个空的Web程序 然后安装Nuget库里面的包 Nancy Nancy.Hosting.Aspnet Nancy.ViewEnglines.Spark 并在We ...
- NancyFx 2.0的开源框架的使用-HosingOwin
Nancy框架的Owin使用 先建一个空的Web项目 然后往Nuget库里面添加Nancy包 Nancy Nancy.Owin Nancy.ViewEnglines.Spark 然后添加Models, ...
- NancyFx 2.0的开源框架的使用-Authentication
新建一个空的项目 新建好了空的项目以后,接着通过NuGet安装一下三个包 Nancy Nancy.Hosting.Aspnet Nancy.ViewEnglines.Razor 然后在项目中添加Mod ...
- NancyFx 2.0的开源框架的使用-Forms
同样的像前面2篇博文一样,每个项目的开始基本都是建个空的Web项目 在NuGet库中安装以下几个NuGet包 Nancy Nancy.Authentication.Forms Nancy.Hostin ...
- NancyFx 2.0的开源框架的使用-AspnetBootstrapping
新建一个空的Web项目AspnetBootstrappingDemo 然后添加NuGet组件 Nancy Nancy.Hosting.Aspnet Nancy.ViewEngines.Razor 继续 ...
- NancyFx 2.0的开源框架的使用-Caching
新建一个空的Web项目,命名CachingDemo 然后添加三个Nuget安装包 Nancy Nancy.Hosting.Aspnet Nancy.ViewsEngines.Razor 然后往项目里面 ...
随机推荐
- 关于ng路由的传参问题(传递一个,多个参数)
在ng的页面条转传参数的方法,ui-sref,$state Ui-sref:用于html页面进行单页面的跳转 $state:用于js代码中跳转 重点:明确传递方,接受方 [传递单个参数] 对于传递方: ...
- 【转】JavaScript中使用ActiveXObject操作本地文件夹的方法
原文链接:http://www.jb51.net/article/48538.htm
- 性能测试培训:tomcat性能调优方法
性能测试培训:tomcat性能调优方法 poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.在poptest的loadrunner ...
- 微信小程序省市联动
最近呢刚好做了一个省市联动的功能,今天看到有人问这个怎么做,我就把我做的放上来共享一下: 首先呢,来看看效果,点击文字'点击',弹出选择窗口,点击取消或者确定(取消.确定按钮在选择框上边,截图有些不清 ...
- C#各个版本中的新增特性详解
序言 自从2000年初期发布以来,c#编程语言不断的得到改进,使我们能够更加清晰的编写代码,也更加容易维护我们的代码,增强的功能已经从1.0搞到啦7.0甚至7.1,每一次改过都伴随着.NET Fram ...
- [Python Web]配置 nginx 遇到错误排查(初级)
配置 nginx 遇到错误排查(初级) 系统版本:ubuntu 14.04,nginx 版本:nginx/1.4.6 (Ubuntu) 本文不是一步步搭建 nginx 的过程,而是我在使用 nginx ...
- 初探CSRF在ASP.NET Core中的处理方式
前言 前几天,有个朋友问我关于AntiForgeryToken问题,由于对这一块的理解也并不深入,所以就去研究了一番,梳理了一下. 在梳理之前,还需要简单了解一下背景知识. AntiForgeryTo ...
- 【shell编程基础0】bash shell编程的基本配置
前面一篇“shell编程之变量篇”主要讲述下shell编程的变量的基本知识:设置变量的方式,自定义变量和环境变量的差别,变量的替换.删除.测试等. 这一篇主要是讲述在bash shell下的一些基本配 ...
- 概念学习 - JNDI, JDBC, ODBC, DataSource
layout: post title: 概念学习 - JNDI, JDBC, ODBC, DataSource --- 最近在学习Java Hibernate,对数据库资源访问这块好多概念模糊,所以在 ...
- 如何快速理解JavaScript 中重要语句for循环
一.基本结构:for(起始状态:判断条件:状态改变){ 执行语句: } 执行顺序:for(var i=1;i<3;i++){ alert(i); } 1.判断条件 2.执行语句 3. ...