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这个框架,在简单的使用之后,发现竟然是如此的简 ...
随机推荐
- [蓝牙] 2、蓝牙BLE协议及架构浅析&&基于广播超时待机说广播事件
第一章 BLE基本概念了解 一.蓝牙4.0和BLE区别 蓝牙4.0是一种应用非常广泛.基于2.4G射频的低功耗无线通讯技术.蓝牙低功耗(Bluetooth Low Energy ),人们又常称之为 ...
- Git Day03,GitHub 1st
1st, SSH key: Add a pic @ Sep 18 2016 20:26 To note the configuration process on Linux: 2nd,github网站 ...
- Java-条件语句、循环语句练习
题目一:一张纸的厚度大约是0.08mm,对折多少次之后能达到珠穆朗玛峰的高度(8848.13米)? double height=0.08; for(int i=1;i>0;i++) { heig ...
- Atitit USRqc62204 证书管理器标准化规范
Atitit USRqc62204 证书管理器标准化规范 /atiplat_cms/src/com/attilax/cert/CertSrv4mv.java /** * */ package com. ...
- Atitit dsl实现(1)------异常的库模式实现 异常的ast结构
Atitit dsl实现(1)------异常的库模式实现 异常的ast结构 1.1. Keyword 1 1.2. 异常的ast模型 1 1.3. Astview的jar org.eclipse. ...
- salesforce 零基础学习(四十)Custom Settings简单使用
有时候,项目中我们需要设置类似白名单的功能,即某些用户或者某种Profile的用户不走一些校验或者走一些校验,这时,使用Custom Settings功能可以很好的解决这一需求. Custom Set ...
- 快速入门系列--CLR--02多线程
最近,由于基础框架的整体升级,因此需要更新所有相关项目的DLL文件.这个过程存在不小的风险,因此也对发布后的生产服务器进行了密切的监控,结果还是出现了个别应用出现异常的情况,很快的占用了大量的服务器内 ...
- JavaScript内存优化
JavaScript内存优化 相对C/C++ 而言,我们所用的JavaScript 在内存这一方面的处理已经让我们在开发中更注重业务逻辑的编写.但是随着业务的不断复杂化,单页面应用.移动HTML5 应 ...
- php分享(三十五) 文件多写注意事项
1: resource fopen ( string $filename , string $mode [, bool $use_include_path = false [,resource $co ...
- Java多线程系列--“JUC集合”07之 ArrayBlockingQueue
概要 本章对Java.util.concurrent包中的ArrayBlockingQueue类进行详细的介绍.内容包括:ArrayBlockingQueue介绍ArrayBlockingQueue原 ...