webapi添加basic认证
2021-01-23 10:15
标签:div 调用 方法 override ide msi count conf abs BasicAbstractAuthorize:抽象类,子类中校验用户名密码,并创建Principal BasicAuthorize:实现类 添加Filter webapi添加basic认证 标签:div 调用 方法 override ide msi count conf abs 原文地址:https://www.cnblogs.com/fanfan-90/p/12074607.html
//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(true).Count > 0
|| actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes(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);
}
}
}
///
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
RegisterFilters(config.Filters);
}
public static void RegisterFilters(HttpFilterCollection filters)
{
filters.Add(new BasicAuthorize());
}