Asp.Net Core 系列教程 (三)身份认证

学习身份认证,请先无比按照教程二,把Postman安装好

Postman国内下载貌似网速很慢讷!

这里附一个下载地址:http://nuget.uuids.cn:1002/postmanx64.exe,这个是我自己搭建的服务器,10m/s,性能一般般,别挤炸了。

好了进入正题。

新建一个Asp.netCore 项目 (我用的VS2019)

VS下载地址:https://visualstudio.microsoft.com/zh-hans/ 版本无所谓,你都混到来看我博客了,计较VS2019的版本 是没意义的。

项目名称 WebAuthorize。其他不变。单击创建 

嗯哼!我们学的 是 身份认证 所以呀! 这里选择 "空"。

 版本什么的 尽量选择和我一样的,其他版本不排除出现 话题之外的问题。.net core 2.0以下的就别用了。

 项目结构非常简单

如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace WebAuthorize
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!").ConfigureAwait(true);
            });
        }
    }
}

进来之后 应用直接给你返回个HelloWorld 结束。

跑一下看看!啊哈!就是这样!

 好了,现在我们加个中间件 过滤请求。

啥加 中间件?这怎么解释!!!

直白点就是 客户端请求到了服务器后,在 控制器和服务器之间加入一层 中间处理层!

还不懂?Ctrl+W 右拐!

打开PostMan。

填写好 参数可以得到下图

接下来我们配置身份认证信息

 

在Authorzation下选 basic Auth, 并把用户名和密码填好

 点一下”Preveiw Request ” PostMan会自动生成请求信息。然后转到Headers下

就可以看到下图

大家可以注意到 左边key 添加了一个Authorization  键值为Basic 一串字符

我们把这串字符 拿到这个网址

http://tool.oschina.net/encrypt?type=3

可以得到下图

啥意思?

其实PostMan 是将 我输入的密码和账号 以字节的形式转换为了base

64 字符串,你要知道 http协议 是超本文,传输字节数据 不方便,所以做了一次转换,(base64 是啥自己 百度)

 

现在我们在代码中打个断点,并让postman再次发下请求。

看下面的动图

我们可以在header 中找到Authorize。 

好了,现在我们编写身份认证类

    public static class LaoWangAuthorizeExtension
    {
        public static void AddLaoWangAuthorize(this IApplicationBuilder applicationBuilder)
        {
            applicationBuilder.Use(async (currentContext,nextContext) =>
            {
                if (currentContext.Request.Headers.ContainsKey("Authorization"))
                {
                    var authorize=  currentContext.Request.Headers["Authorization"].ToString();
                    if (authorize.Contains("Basic"))//如果是Basic 身份认证
                    {
                        var info= authorize.Replace("Basic ", string.Empty);
                        var bytes=  Convert.FromBase64String(info);//反解析Basic 64
                        var contents=   Encoding.Default.GetString(bytes);
                        var dd=  contents.Split(":").ToArray();
                        var userName = dd[0];//用户名
                        var userPwd = dd[1];//密码
                        if (userName== "GeBiLaoWang"&&userPwd=="123456")
                        {
                            await currentContext.Response.WriteAsync("验证通过").ConfigureAwait(true);
                            await nextContext?.Invoke();
                            return;
                        }
                    }
                }
                currentContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                await currentContext.Response.WriteAsync("See tou tomorrow!").ConfigureAwait(true);

            });
        }
    }

然后将代码修改为如下

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.AddLaoWangAuthorize();
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!").ConfigureAwait(true);
            });
        }

启动 浏览器查看。

 

因为我们代码做了拦截 ,所以

这里直接 再见了!

再看下 postman

当我们用错误的账号时

当我们用正确的账号时

身份认证就是这么简单。 

源代码  见我的下载区

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值