关于web api 验证
两种验证方式
1.客户端post请求
发送代码:
var r = WebRequest.Create(param.Url) as HttpWebRequest; //param.AuthorizeCode 验证参数 if (!string.IsNullOrEmpty(param.AuthorizeCode)&& !string.IsNullOrEmpty(param.AuthorizeName)) { string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{param.AuthorizeCode}:{param.AuthorizeName}")); r.Headers.Add("Authorization", $"Basic {encoded}"); }
接收代码:
public class RequestAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(HttpActionContext actionContext) { //从http请求的头里面获取身份验证信息,验证是否是请求发起方的ticket var authorization = actionContext.Request.Headers.Authorization; if ((authorization != null) && (authorization.Parameter != null)) { //解密用户ticket,并校验用户名密码是否匹配 var encryptTicket = authorization.Parameter; if (ValidateTicket(encryptTicket)) { base.IsAuthorized(actionContext); } else { HandleUnauthorizedRequest(actionContext); } } //如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401 else { var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>(); bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute); if (isAnonymous) base.OnAuthorization(actionContext); else HandleUnauthorizedRequest(actionContext); } } //校验用户名密码(正式环境中应该是数据库校验) private bool ValidateTicket(string encryptTicket) { byte[] c = Convert.FromBase64String(encryptTicket); string a = System.Text.Encoding.Default.GetString(c); //解密Ticket //从Ticket里面获取用户名和密码 var index = a.IndexOf(":"); string strUser = a.Substring(0, index); string strPwd = a.Substring(index + 1); if (strUser == "admin" && strPwd == "123456") { return true; } else { return false; } } }
2.ajax方式调用
发送代码:
$(function () { $.ajax({ type: "get", url: "http://localhost:27221/api/Charging/GetAllChargingData", data: {}, beforeSend: function (XHR) { //发送ajax请求之前向http的head里面加入验证信息 XHR.setRequestHeader('Authorization', 'BasicAuth ' + Ticket); }, success: function (data, status) { if (status == "success") { $("#div_test").html(data); } }, error: function (e) { $("#div_test").html("Error"); }, complete: function () { } }); });
接收代码:
/// <summary> /// 自定义此特性用于接口的身份验证 /// </summary> public class RequestAuthorizeAttribute : AuthorizeAttribute { //重写基类的验证方式,加入我们自定义的Ticket验证 public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { //从http请求的头里面获取身份验证信息,验证是否是请求发起方的ticket var authorization = actionContext.Request.Headers.Authorization; if ((authorization != null) && (authorization.Parameter != null)) { //解密用户ticket,并校验用户名密码是否匹配 var encryptTicket = authorization.Parameter; if (ValidateTicket(encryptTicket)) { base.IsAuthorized(actionContext); } else { HandleUnauthorizedRequest(actionContext); } } //如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401 else { var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>(); bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute); if (isAnonymous) base.OnAuthorization(actionContext); else HandleUnauthorizedRequest(actionContext); } } //校验用户名密码(正式环境中应该是数据库校验) private bool ValidateTicket(string encryptTicket) { //解密Ticket var strTicket = FormsAuthentication.Decrypt(encryptTicket).UserData; //从Ticket里面获取用户名和密码 var index = strTicket.IndexOf("&"); string strUser = strTicket.Substring(0, index); string strPwd = strTicket.Substring(index + 1); if (strUser == "admin" && strPwd == "123456") { return true; } else { return false; } } }
参考:https://www.cnblogs.com/landeanfen/p/5287064.html