1、新建UserDatabase类,实现IUserMapper接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;

using Nancy.Authentication.Forms;

public class UserDatabase : IUserMapper
{
private static List<Tuple<string, string, Guid>> users = new List<Tuple<string, string, Guid>>();

static UserDatabase()
{
users.Add(new Tuple<string, string, Guid>("admin", "password", new Guid("55E1E49E-B7E8-4EEA-8459-7A906AC4D4C0")));
users.Add(new Tuple<string, string, Guid>("user", "password", new Guid("56E1E49E-B7E8-4EEA-8459-7A906AC4D4C0")));
}

public ClaimsPrincipal GetUserFromIdentifier(Guid identifier, NancyContext context)
{
var userRecord = users.FirstOrDefault(u => u.Item3 == identifier);

return userRecord == null
? null
: new ClaimsPrincipal(new ClaimsIdentity(BuildClaims(userRecord.Item1), "querystring"));
}

public static Guid? ValidateUser(string username, string password)
{
var userRecord = users.FirstOrDefault(u => u.Item1 == username && u.Item2 == password);

if (userRecord == null)
{
return null;
}

return userRecord.Item3;
}

/// <summary>
/// Build claims based on username
/// </summary>
/// <param name="userName">Current username</param>
/// <returns>IEnumerable of claims</returns>
private static IEnumerable<Claim> BuildClaims(string userName)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Role, userName));
return claims;
}
}

2、新建FormsAuthBootstrapper启动类

using Nancy.Authentication.Forms;
using Nancy.Bootstrapper;
using Nancy.TinyIoc;

public class FormsAuthBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
// We don't call "base" here to prevent auto-discovery of
// types/dependencies
}

protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
{
base.ConfigureRequestContainer(container, context);

// Here we register our user mapper as a per-request singleton.
// As this is now per-request we could inject a request scoped
// database "context" or other request scoped services.
container.Register<IUserMapper, UserDatabase>();
}

protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
{
// At request startup we modify the request pipelines to
// include forms authentication - passing in our now request
// scoped user name mapper.
//
// The pipelines passed in here are specific to this request,
// so we can add/remove/update items in them as we please.
var formsAuthConfiguration =
new FormsAuthenticationConfiguration()
{
RedirectUrl = "~/login",
UserMapper = requestContainer.Resolve<IUserMapper>(),
};

FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
}
}

3、登录方法实现

Post["/login"] = x => {
var userGuid = UserDatabase.ValidateUser((string)this.Request.Form.Username, (string)this.Request.Form.Password);

if (userGuid == null)
{
return this.Context.GetRedirect("~/login?error=true&username=" + (string)this.Request.Form.Username);
}

DateTime? expiry = null;
if (this.Request.Form.RememberMe.HasValue)
{
expiry = DateTime.Now.AddDays(7);
}

return this.LoginAndRedirect(userGuid.Value, expiry);
};

4、需要授权地方使用

Get["/secured"] = x => {
this.RequiresAuthentication();//需要登录才能访问,否则返回bootstrap配置中的地址。
this.RequiresClaims(c => c.Type == ClaimTypes.Role && c.Value == "admin");//申明了admin的角色才可访问,否则403

//this.RequiresAnyClaim(h=>h.Value== "admin"||h.Value=="User"); //申明值为admin或user的均可访问,否则403

var model = new UserModel(this.Context.CurrentUser.Identity.Name);
return View["secure.cshtml", model];
};

Nancy FormsAuthentication使用的更多相关文章

  1. Nancy之Forms authentication的简单使用

    一.前言 想必大家或多或少都听过微软推出的ASP.NET Identity技术,可以简单的认为就是一种授权的实现 很巧的是,Nancy中也有与之相类似的技术Authentication,这两者之间都用 ...

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

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

  3. Nancy简单实战之NancyMusicStore(三):完善商品信息与管理

    前言 上一篇,我们做了不少准备,并且还把我们NancyFx音乐商城的首页打造好了.这一篇主要是完善我们在首页的商品浏览问题和添加对商品的管理. 下面开始正题: 商品详情 首先是查看单个商品的详情: 先 ...

  4. Nancy Web框架

    原文 Nancy Web框架 Nancy框架 一.创建第一个Nancy应用 二.探索Nancy的module 1. 模块能够在全局被发现 2. 使用模块为路由创建一个根 三.定义路由 1. 方法 2. ...

  5. Nancy之大杂烩

    Nancy关于Hosting的简单介绍 一. Nancy之基于Nancy.Hosting.Aspnet的小Demo 二.Nancy之基于Nancy.Hosting.Self的小Demo 三.Nancy ...

  6. Nancy之实现API的功能

    0x01.前言 现阶段,用来实现API的可能大部分用的是ASP.NET Web API或者是ASP.NET MVC,毕竟是微软官方出产的,用的人也多. 但是呢,NancyFx也是一个很不错的选择.毕竟 ...

  7. 第二章 Rest框架 Nancy

    正如你看到的,Nancy有两个主要用途. 其中第一项是作为一种通用的基于 REST 框架,可替代 ASP.NET Web API 或其他Rest工具包. 默认情况下,Nancy提供一流的路由和内容协商 ...

  8. 在Linux中运行Nancy应用程序

    最近在研究如何将.NET应用程序移植到非Windows操作系统中运行,逐渐会写一些文章出来.目前还没有太深的研究,所以这些文章大多主要是记录我的一些实验. 这篇文章记录了我如何利用NancyFx编写一 ...

  9. [Nancy On .Net Core Docker] 轻量级的web框架

    .net core现在已经有了大的发展,虽然笔者现在已经从事python开发,但是一直在关注.net的发展,在逛博客园的时候,发现有大家都会提到Nancy这个框架,在简单的使用之后,发现竟然是如此的简 ...

随机推荐

  1. 如何为编程爱好者设计一款好玩的智能硬件(八)——LCD1602点阵字符型液晶显示模块驱动封装(中)

    六.温湿度传感器DHT11驱动封装(下):如何为编程爱好者设计一款好玩的智能硬件(六)——初尝试·把温湿度给收集了(下)! 七.点阵字符型液晶显示模块LCD1602驱动封装(上):如何为编程爱好者设计 ...

  2. js模版引擎handlebars.js实用教程——with-终极this应用

    返回目录 <!DOCTYPE html> <html> <head> <META http-equiv=Content-Type content=" ...

  3. 人机大战之AlphaGo的硬件配置和算法研究

    AlphaGo的硬件配置 最近AlphaGo与李世石的比赛如火如荼,关于第四盘李世石神之一手不在我们的讨论范围之内.我们重点讨论下AlphaGo的硬件配置: AlphaGo有多个版本,其中最强的是分布 ...

  4. How to Change RabbitMQ Queue Parameters in Production?

    RabbitMQ does not allow re-declaring a queue with different values of parameters such as durability, ...

  5. 通过 Redis 实现 RPC 远程方法调用(支持多种编程语

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/101.html?1455869487 我发现经常研究并且为之兴奋的一件事就 ...

  6. sql基础知识:分页+排序

    Oracle的分页还真是挺恶心地,不像mysql直接Limit就搞定 select name from student limit 0,20; Oracle需要借助rownum实现: select * ...

  7. asp.net 文件 操作方法

    /// <summary> /// 移动文件 /// </summary> /// <param name="oldPath">源文件路径< ...

  8. angularjs学习曲线

    angularjs学习曲线 刚开始学Augular觉得开发应用需要有相当的编程基础. 不得不说这确实是一款了不起的开发框架,它要求开发人员设计低耦合和可维护的应用. 使用AngularJS 的复杂度就 ...

  9. HTTP学习四:SPDY和HTTP/2.0

    1 HTTP1.0/1.1与HTTPS的不足 1.1 HTTP1.0/1.1不足 单路连接 HTTP 协议的最大弊端就是每个 TCP 连接只能对应一个 HTTP 请求,即每个 HTTP 连接只请求一个 ...

  10. Python中的魔法方法

    1.什么是魔法方法? 魔法方法就是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,你可以定义自己想要的行为,而这一 ...