.NET Core登录api时使用Basic认证

1.建立一个正常运行的.net core web api项目,并且能运行。

2.增加BasicMiddleware类

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApplication6
{
    public class BasicMiddleware
    {
        private readonly RequestDelegate _next;
        public const string AuthorizationHeader = "Authorization";
        public const string WWWAuthenticateHeader = "WWW-Authenticate";
        private BasicUser _user;
        public BasicMiddleware(RequestDelegate next, BasicUser user)
        {
            _next = next;
            _user = user;
        }

        public Task Invoke(HttpContext httpContext)
        {
            var Request = httpContext.Request;
            string auth = Request.Headers[AuthorizationHeader];
            if (auth == null)
            {
                return BasicResult(httpContext);
            }
            //取得Base64 并解码成字符串
            string[] authParts = auth.Split(' ');
            if (authParts.Length != 2)
                return BasicResult(httpContext);
            string base64 = authParts[1];
            string authValue;
            try
            {
                byte[] bytes = Convert.FromBase64String(base64);
                authValue = Encoding.ASCII.GetString(bytes);
            }
            catch
            {
                authValue = null;
            }
            if (string.IsNullOrEmpty(authValue))
                return BasicResult(httpContext);

            // 解析用户名密码
            string userName;
            string password;
            int sepIndex = authValue.IndexOf(':');
            if (sepIndex == -1)
            {
                userName = authValue;
                password = string.Empty;
            }
            else
            {
                userName = authValue.Substring(0, sepIndex);
                password = authValue.Substring(sepIndex + 1);
            }
            //判断用户名密码
            if (_user.UserName.Equals(userName) && _user.Password.Equals(password))
                return _next(httpContext);
            else
                return BasicResult(httpContext);
        }
        /// <summary>
        /// 返回需Basic 认证输出
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        private static Task BasicResult(HttpContext httpContext)
        {
            httpContext.Response.StatusCode = 401;
            httpContext.Response.Headers.Add(WWWAuthenticateHeader, "Basic realm=\"localhost\"");
            return Task.FromResult(httpContext);
        }
    }

    public static class BasicMiddlewareExtensions
    {
        public static IApplicationBuilder UseBasicMiddleware(this IApplicationBuilder builder, BasicUser user)
        {
            if (user == null)
                throw new ArgumentException("需设置Basic用户");
            return builder.UseMiddleware<BasicMiddleware>(user);
        }
    }
}

3.建立BasicUser类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6
{
    public class BasicUser
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}

4.在Startup.cs类中的Configure方法中使用中间件,并且设置账号和密码

            app.UseBasicMiddleware(new BasicUser { 
             UserName="admin", Password="123456"
            });

5.运行网址,点击执行,弹框

6.输入账号密码

7.效果,顺利返回数值 

 一般这种认证都是比较弱的,可以使用JWT代替。

来源:.NET Core登录api时使用Basic认证_netcore basic_故里2130的博客-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

故里2130

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值