Nancy FormsAuthentication使用
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使用的更多相关文章
- Nancy之Forms authentication的简单使用
一.前言 想必大家或多或少都听过微软推出的ASP.NET Identity技术,可以简单的认为就是一种授权的实现 很巧的是,Nancy中也有与之相类似的技术Authentication,这两者之间都用 ...
- Nancy 学习-身份认证(Forms authentication) 继续跨平台
开源 示例代码:https://github.com/linezero/NancyDemo 上篇讲解Nancy的Basic Authentication,现在来学习Nancy 的Forms身份认证. ...
- Nancy简单实战之NancyMusicStore(三):完善商品信息与管理
前言 上一篇,我们做了不少准备,并且还把我们NancyFx音乐商城的首页打造好了.这一篇主要是完善我们在首页的商品浏览问题和添加对商品的管理. 下面开始正题: 商品详情 首先是查看单个商品的详情: 先 ...
- Nancy Web框架
原文 Nancy Web框架 Nancy框架 一.创建第一个Nancy应用 二.探索Nancy的module 1. 模块能够在全局被发现 2. 使用模块为路由创建一个根 三.定义路由 1. 方法 2. ...
- Nancy之大杂烩
Nancy关于Hosting的简单介绍 一. Nancy之基于Nancy.Hosting.Aspnet的小Demo 二.Nancy之基于Nancy.Hosting.Self的小Demo 三.Nancy ...
- Nancy之实现API的功能
0x01.前言 现阶段,用来实现API的可能大部分用的是ASP.NET Web API或者是ASP.NET MVC,毕竟是微软官方出产的,用的人也多. 但是呢,NancyFx也是一个很不错的选择.毕竟 ...
- 第二章 Rest框架 Nancy
正如你看到的,Nancy有两个主要用途. 其中第一项是作为一种通用的基于 REST 框架,可替代 ASP.NET Web API 或其他Rest工具包. 默认情况下,Nancy提供一流的路由和内容协商 ...
- 在Linux中运行Nancy应用程序
最近在研究如何将.NET应用程序移植到非Windows操作系统中运行,逐渐会写一些文章出来.目前还没有太深的研究,所以这些文章大多主要是记录我的一些实验. 这篇文章记录了我如何利用NancyFx编写一 ...
- [Nancy On .Net Core Docker] 轻量级的web框架
.net core现在已经有了大的发展,虽然笔者现在已经从事python开发,但是一直在关注.net的发展,在逛博客园的时候,发现有大家都会提到Nancy这个框架,在简单的使用之后,发现竟然是如此的简 ...
随机推荐
- Android自定义View的构造函数
自定义View是Android中一个常见的需求,每个自定义的View都需要实现三个基本的构造函数,而这三个构造函数又有两种常见的写法. 第一种 每个构造函数分别调用基类的构造函数,再调用一个公共的初始 ...
- Lua字符串库(整理)
Lua字符串库小集 1. 基础字符串函数: 字符串库中有一些函数非常简单,如: 1). string.len(s) 返回字符串s的长度: 2). string.rep(s,n) 返回 ...
- Atitit图片复制父目录给你设计的实现 基于win 图片浏览器
Atitit图片复制父目录给你设计的实现 基于win 图片浏览器 打开属性,获取其路径...1 Ahk参数传递,使用环境变量即可1 如何ahk异常转换为java异常1 如何获取ahk的输出.1 C:\ ...
- ui-router带参数的路由配置
ui-router带参数的路由配置 使用ng-route的时候带参数的连接这样配置: $routeProvider.when('item/itemid/:itemid', { templateUrl: ...
- Python字符串的encode与decode
首先要搞清楚,字符串在Python内部的表示是unicode编码. 因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unic ...
- 探讨Nodejs中的作用域问题。
在JS中有全局作用域和函数作用域,而在Nodejs中也自己的作用域,分为全局作用域(global)和模块作用域. js作用域: 以前学js的时候我们的全局对象是window,如: var a = 10 ...
- Visual Studio Emulator for Android 里面的安卓模拟器如何启用
打开软件
- 将 PAGE_VERIFY 数据库选项设置为 CHECKSUM
此规则检查 PAGE_VERIFY 数据库选项是否已设置为 CHECKSUM.为 PAGE_VERIFY 数据库选项启用 CHECKSUM 后,SQL Server 数据库引擎会在向磁盘中写入页面时计 ...
- WPF自定义控件与样式(5)-Calendar/DatePicker日期控件自定义样式及扩展
一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要内容: 日历控 ...
- vc++用ADO方式连接oracle问题
今天装了个oracle客户端,准备写个访问远程oracle的程序.用的是vs2010,采用ADO的连接方法连接oracle,结果运行的时候总是报下面的错: 从提示可以看出是没有找到OraOLEDBup ...