• webapi添加basic认证


     

    BasicAbstractAuthorize:抽象类,子类中校验用户名密码,并创建Principal 

    BasicAuthorize:实现类

        //base.OnAuthorization(),此方法内部,调用IsAuthorized()判断是否授权,如果未授权调用HandleUnauthorizedRequest()方法
        //base.IsAuthorized(),判断Principal、Identity是否为空,为空则未授权
        //base.HandleUnauthorizedRequest(),此方法内部创建Response,状态码401;
        //
        public abstract class BasicAbstractAuthorize : AuthorizeAttribute
        {
            public override void OnAuthorization(HttpActionContext actionContext)
            {
    
                var authenticationHeader = actionContext.Request.Headers.Authorization;
    
                if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count > 0
                    || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count > 0)
                {//如果有AllowAnonymous特性,就不检查
                    base.OnAuthorization(actionContext);
                }
                else
                {
                    if (authenticationHeader != null && authenticationHeader.Scheme == "Basic" && !string.IsNullOrEmpty(authenticationHeader.Parameter))
                    {
                        var userNameAndPassword = this.GetUserNameAndPassword(authenticationHeader.Parameter);
                        actionContext.RequestContext.Principal = this.Authenticate(userNameAndPassword.Item1, userNameAndPassword.Item2, actionContext);
                    }
                    if (actionContext.RequestContext.Principal == null)
                    {
                        base.HandleUnauthorizedRequest(actionContext);
                    }
                }
    
            }
            /// <summary>
            /// 校验用户名、密码
            /// </summary>
            /// <returns></returns>
            public abstract IPrincipal Authenticate(string userName, string password, HttpActionContext actionContext);
            /// <summary>
            /// 获取用户名、密码
            /// </summary>
            /// <param name="authenticationParameter"></param>
            /// <returns></returns>
            private Tuple<string, string> GetUserNameAndPassword(string authenticationParameter)
            {
                if (!string.IsNullOrWhiteSpace(authenticationParameter))
                {
                    var data = Encoding.ASCII.GetString(Convert.FromBase64String(authenticationParameter)).Split(':');
                    return new Tuple<string, string>(data[0], data[1]);
                }
                return null;
            }
        }
    
        public class BasicAuthorize : BasicAbstractAuthorize
        {
            public override IPrincipal Authenticate(string userName, string password, HttpActionContext actionContext)
            {
                //校验用户名、密码
                if (userName == "zhangsan" && password == "123")
                {
                    ClaimsIdentity identity = new ClaimsIdentity(new List<Claim> {
                        new Claim("UserName",userName)
                    });
                    ClaimsPrincipal principal = new ClaimsPrincipal(identity);
                    return principal;
                }
                return null;
    
            }
        }

     添加Filter

            public static void Register(HttpConfiguration config)
            {
                // Web API 配置和服务
                RegisterFilters(config.Filters);
            }
            public static void RegisterFilters(HttpFilterCollection filters)
            {
                filters.Add(new BasicAuthorize());
            }
  • 相关阅读:
    codeforces#571Div2 D---Vus the Cossack and Numbers【贪心】
    洛谷P1050 循环【java大数】
    洛谷P1972 HH的项链【树状数组】
    uoj#67 新年的毒瘤【Tarjan】
    洛谷1265 公路修建【最小生成树】
    【超实用工具】三维场景绘制工具
    坐标地址批处理工具
    CAD转KML乱码处理
    地理编码逆编码教程
    最新!全球ALOS 12m地形数据介绍及下载
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12074607.html
Copyright © 2020-2023  润新知