Nancy 学习-身份认证(Basic Authentication) 继续跨平台
开源 示例代码:https://github.com/linezero/NancyDemo
前面讲解Nancy的进阶部分,现在来学习Nancy 的身份认证。
本篇主要讲解Basic Authentication ,基本认证。
在HTTP中,基本认证是一种用来允许Web浏览器或其他客户端程序在请求时提供用户名和口令形式的身份凭证的一种登录验证方式。
说明:本篇示例是基于 Nancy 1.4.3。Nancy 2.0预览版 已经发布,版本改动较大,故特此说明。
准备
安装 Nancy.Authentication.Basic
Install-Package Nancy.Authentication.Basic -Version 1.4.1
我这里就不新建项目了,直接在之前的项目中进行添加。
1.实现IUserValidator 接口
新建一个类,实现IUserValidator接口。
public class BasicUserValidator:IUserValidator { public IUserIdentity Validate(string username, string password) { if (username == "linezero" && password == "demo") { return new BasicUser() { UserName = username }; } return null; } }
这里我将用户判断固定了,大家也可以自己使用各种方式去判断。
2.实现IUserIdentity 接口
public class BasicUser : IUserIdentity { public string UserName { get; set; } public IEnumerable<string> Claims { get; set; } }
3.在Nancy管道中添加认证
在继承 DefaultNancyBootstrapper 的 Bootstrapper 中的 ApplicationStartup 添加如下代码:
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration( container.Resolve<IUserValidator>(), "MyRealm"));//Basic认证添加 pipelines.OnError += Error; }
主要代码:
pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration( container.Resolve<IUserValidator>(), "MyRealm"));
添加好以后,启动程序。
访问:http://localhost:9000
输入linezero demo 成功认证。
4. 获取授权用户
我们要在module 中获取授权用户使用 Context.CurrentUser 就可以获取到用户信息。
在HomeModule 中添加一个获取用户名:
Context.CurrentUser.UserName
实现如下:
5.跨平台
将程序上传至linux执行,访问 对应地址:
示例代码下载:https://github.com/linezero/NancyDemo
示例代码包含之前示例,并且会持续更新,欢迎大家Star。
如果你觉得本文对你有帮助,请点击“推荐”,谢谢。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?