欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

WebAPI笔记:用户身份验证(basic验证)

程序员文章站 2022-06-16 09:34:36
测试代码链接webapi用户身份验证:Form身份验证 Basic window集成 摘要 OAuth案例使用basic验证;BasicAuthorizeAttribute : AuthorizeAttribute 只要带有BasicAuthorizeAttribute特性的控制器或控制器api都会在api执行前进行身份验证basic验证流程:在用户登录时记录票证Ticket(用户账号密码加密字符串)可存session中,也可以利用其他缓存技术存储实现多服务器共享用户身份验证,跨域验证。。...

测试代码链接

webapi用户身份验证:Form身份验证 Basic window集成 摘要 OAuth

案例使用basic验证;BasicAuthorizeAttribute : AuthorizeAttribute 只要带有BasicAuthorizeAttribute特性的控制器或控制器api都会在api执行前进行身份验证

basic验证流程:
在用户登录时记录票证Ticket(用户账号密码加密字符串)可存session中,也可以利用其他缓存技术存储实现多服务器共享用户身份验证,跨域验证。。。

浏览器客户端调用webapi时需要在执行ajax请求时向Request Header设置authorization: BasicAuth 票证Ticket(可封装js)

        //模拟登录,记录票证Ticket
        [HttpGet]
        [Route("api/Login")]
        [AllowAnonymous]
        public string Login(string account, string password)
        {
            if (account.Equals("Admin") && password.Equals("123456"))
            {
                FormsAuthenticationTicket ticketObject = new FormsAuthenticationTicket(0, account, DateTime.Now,
                            DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", account, password),
                            FormsAuthentication.FormsCookiePath);
                var result = new { Result = true, Ticket = FormsAuthentication.Encrypt(ticketObject) };
                return JsonConvert.SerializeObject(result);
            }
            else
            {
                var result = new { Result = false };
                return JsonConvert.SerializeObject(result);
            }
        }
            var ticket = "";//登陆后票证Ticket放在某个html里面,测试用,刷新页面将失效
            //测试用户身份验证,有票证Ticket,可以验证通过
            $("#btnGet3").on("click", function () {
                $.ajax({
                    url: '/api/ValuesGet/' + $("#txtId").val(), type: "get", 
                    beforeSend: function (XHR) { //xhr XML Http Request
                        //发送ajax请求之前向http的head里面加入验证信息,所有需要用户身份验证的ajax都要带上,可以封装js实现
                        XHR.setRequestHeader('Authorization', 'BasicAuth ' + ticket);
                    }, 
                    success: function (data) {
                        alert(data);
                    }, datatype: "json"
                });
            });

后端在带有 [BasicAuthorizeAttribute]特性api在被执行前会进行身份验证
[AllowAnonymous]特性跳过身份验证

basic验证特性BasicAuthorizeAttribute

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Security;

namespace ThirdWebApi.Unity
{
    /// <summary>
    /// basic验证
    /// </summary>
    public class BasicAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 发生请求前去完成验证
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var authorization = actionContext.Request.Headers.Authorization;

            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0
                || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0)
            {
                base.OnAuthorization(actionContext);//正确的访问方法
            }
            else if (authorization != null && authorization.Parameter != null)
            {
                //用户验证逻辑
                if (ValidateTicket(authorization.Parameter))
                {
                    base.IsAuthorized(actionContext);//正确的访问方法
                }
                else
                {
                    this.HandleUnauthorizedRequest(actionContext);//没有权限
                }
            }
            else
            {
                this.HandleUnauthorizedRequest(actionContext);//没有权限
            }
        }

        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);//告诉浏览器要验证
            challengeMessage.Headers.Add("WWW-Authenticate", "Basic");//权限信息放在basic
            //throw new System.Web.Http.HttpResponseException(challengeMessage);

            base.HandleUnauthorizedRequest(actionContext);//返回没有授权
        }

        private bool ValidateTicket(string encryptTicket)
        {
            //解密Ticket
            var strTicket = FormsAuthentication.Decrypt(encryptTicket).UserData;
            return string.Equals(strTicket, string.Format("{0}&{1}", "Admin", "123456"));
            //应该分拆后去数据库验证
        }
    }
}

本文地址:https://blog.csdn.net/qq_39827640/article/details/107623724

相关标签: WebApi