zoukankan      html  css  js  c++  java
  • 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。

    如果你觉得本文对你有帮助,请点击“推荐”,谢谢。

  • 相关阅读:
    Python学习--not语句
    【图论】有向无环图的拓扑排序
    算法精解:DAG有向无环图
    Python xrange() 函数
    自然语言处理课程(二):Jieba分词的原理及实例操作
    Jieba分词原理与解析
    ios面试题整理
    OC语言Block和协议
    OC内存管理
    IOS 开发-- 常用-- 核心代码
  • 原文地址:https://www.cnblogs.com/linezero/p/5257912.html
Copyright © 2011-2022 走看看