• WebAPI学习笔记(1)实现Basic Auth基本授权验证


    1、Http基本认证只需要添加新的认证过滤属性。该属性类继承自 System.Web.Http.AuthorizeAttribute,在 IsAuthorized(...)方法中读取Http 头部Authorization字段及其值,进行自定义验证。

     1 public class HttpBasicAuthAttribute : System.Web.Http.AuthorizeAttribute
     2     {
     3         public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
     4         {
     5             //从http请求的头里面获取身份验证信息,验证是否是请求发起方的ticket
     6             var authorization = actionContext.Request.Headers.Authorization;
     7             if ((authorization != null) && (authorization.Parameter != null))
     8             {
     9                 //解密用户ticket,并校验用户名密码是否匹配
    10                 var encryptTicket = authorization.Parameter;
    11                 if (ValidateTicket(encryptTicket))
    12                 {
    13                     base.IsAuthorized(actionContext);
    14                 }
    15                 else
    16                 {
    17                     HandleUnauthorizedRequest(actionContext);
    18                 }
    19             }
    20             //如果取不到身份验证信息,则返回未验证401
    21             else
    22             {
    23                 HandleUnauthorizedRequest(actionContext);
    24             }
    25         }
    26 
    27         //校验用户名密码(正式环境中应该是数据库校验)
    28         private bool ValidateTicket(string encryptTicket)
    29         {
    30             //解密Ticket
    31             string strTicket = System.Text.Encoding.Default.GetString(Convert.FromBase64String(encryptTicket));
    32 
    33             //从Ticket里面获取用户名和密码
    34             var index = strTicket.IndexOf(":");
    35             string strUser = strTicket.Substring(0, index);
    36             string strPwd = strTicket.Substring(index + 1);
    37 
    38             if (strUser == "admin" && strPwd == "123456")
    39             {
    40                 return true;
    41             }
    42             else
    43             {
    44                 return false;
    45             }
    46         }
    47     }

    2、在需要验证的具体Controller类或封装的基类中添加HttpBasicAuthAttribute类属性。

     1 [HttpBasicAuth]
     2 public class BaseController : ApiController
     3 {
     4         private string _adminUserToken = "";
     5 
     6         /// <summary>
     7         /// Admin User Token
     8         /// </summary>
     9         public string AdminUserToken
    10         {
    11             get { return _adminUserToken; }
    12             set { _adminUserToken = value; }
    13         }
    14 }

    3、这样就完成了服务器端的设置。

    4、用Postman调用:

    5、Asp.net调用:

     1 string Username = "admin";
     2 string Password = "123456";
     3 using (HttpClient client = new HttpClient())
     4 {
     5     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}")));
     6 
     7     HttpContent httpContent = new StringContent("", Encoding.UTF8);
     8     httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
     9     Uri address = new Uri("https://xxx/api/issues");
    10 
    11     var response = client.PostAsync(address, httpContent).Result.Content.ReadAsStringAsync().Result;//返回值
    12 }

    6、返回结果:

    【原文出处】http://www.51aras.com/?id=39

      

  • 相关阅读:
    解决eclipsehelios中Errors running builder JavaScript Validator的问题
    oracle sequence cache
    离开页面前调用Js方法
    精典的148句话
    DB2 应用
    现有portal项目(商业的和开源的)解决方案及优缺点
    管理铁律
    myeclipse 6.0 弹出 Multiple Errors have Occurred 错误
    绝对经典的表记录操作(超越版)
    DB2中不同于其它数据库的操作
  • 原文地址:https://www.cnblogs.com/61007257Steven/p/11717880.html
Copyright © 2020-2023  润新知