zoukankan      html  css  js  c++  java
  • 以Attribute加上Header验证

    建立新FilterAttribute继承AuthorizationFilterAttribute,覆写OnAuthorization拦截传入的HttpActionContext内容判断是否有传入指定的资料

    public override void OnAuthorization(HttpActionContext filterContext)
    {
    var identity = FetchAuthHeader(filterContext); //取得資料內容
    if (identity == null)
    {
    ChallengeAuthRequest(filterContext); //回傳錯誤訊息
    return;
    }
    var genericPrincipal = new GenericPrincipal(identity, null);
    //針對目前連線的使用者做授權 
    Thread.CurrentPrincipal = genericPrincipal;
    if (!OnAuthorizeUser(identity.Name, identity.Password, filterContext)) //驗證
    {
    ChallengeAuthRequest(filterContext);
    return;
    }
    base.OnAuthorization(filterContext);
    }
    

    解析HttpActionContext内容取得指定的资料

    protected virtual BasicAuthenticationIdentity FetchAuthHeader(HttpActionContext filterContext)
    {
    string customer = "";
    string pwd = "";
    IEnumerable<string> authRequest = filterContext.Request.Headers.GetValues("指定的資料名稱");
    IEnumerable<string> authRequest2 = filterContext.Request.Headers.GetValues("指定的資料名稱2");
    try
    {
    customer = authRequest.FirstOrDefault();
    pwd = authRequest2.FirstOrDefault();
    }
    catch { }
    return new BasicAuthenticationIdentity(customer, pwd);
    }
    

    验证解析出来的资料是否符合需求

    protected override bool OnAuthorizeUser(string username, string password, HttpActionContext actionContext)
    {
    if (username == "驗證資料" && password == "驗證碼")
    return true;
    return false;
    }
    

    建立验证失败时要回传的讯息

    private static void ChallengeAuthRequest(HttpActionContext filterContext)
    {
    var dnsHost = filterContext.Request.RequestUri.DnsSafeHost;
    filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
    filterContext.Response.Headers.Add("WWW-Authenticate", string.Format("validate failed", dnsHost));
    }
    

    于WebApiConfig.cs中注册新增的Filter

    public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {
    GlobalConfiguration.Configuration.Filters.Add(new WebApi.Filters.ApiAuthenticationFilter());
    }
    }
    

    最后在需要验证的API加上该Filter即可

    [WebApi.Filters.ApiAuthenticationFilter]
    public object QueryApi(string pInput)
    { 
    return null; 
    }
    

    转载自:AlenWu的程式学习笔记

  • 相关阅读:
    git 删除远程文件、文件夹
    pod install太慢 可以使用代理的方式
    flutter Container()最小宽度 最小高度
    flutter common init 常用Widget初始化
    xcode 嵌入flutter_module后编译报错 This app could not be installed at this time.
    Spring AOP
    Spring @Value 配置项解析 vs Spring @ConfigurationProperties 配置项解析
    Spring Bean 的实例化过程
    SpringBoot 配置项解析
    Spring IOC 自动注入流程
  • 原文地址:https://www.cnblogs.com/hnsongbiao/p/9381303.html
Copyright © 2011-2022 走看看