建立新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的程式学习笔记

以Attribute加上Header验证的更多相关文章

  1. webapi swagger自定义 HTTP Header验证用户

    问题描述 webapi自定义的一种验证方式(token放入header里),使用swagger测试时由于header里没值所以一直拿不到用户. 解决如下:(从标题2开始,标题1处处理全局验证用户) 1 ...

  2. asp.net web form中 用attribute实现权限验证方式

    以前项目的代码比较陈旧,今天抽空优化了一下.作为记录. 以前每次请求一个方法都要验证是否登录 if xxx等  现在通过global文件中的改进 反射这个方法的属性是否需要权限 要的话先验证权限.以下 ...

  3. Webservice加上SoapHeader验证方式

    提供一种基于SoapHeader的自定义验证方式,代码如下: public class MySoapHeader : System.Web.Services.Protocols.SoapHeader ...

  4. webservice jaxws header验证

    @WebService @HandlerChain public class UserService { ... } package com.xx.ws.header; import org.w3c. ...

  5. 【微信小程序】request请求POST提交数据,记得要加上header

    wx.request({ url: '*******', data: { "type":"nearest_village", "district&qu ...

  6. Python爬虫--抓取糗事百科段子

    今天使用python爬虫实现了自动抓取糗事百科的段子,因为糗事百科不需要登录,抓取比较简单.程序每按一次回车输出一条段子,代码参考了 http://cuiqingcai.com/990.html 但该 ...

  7. Net中Attribute特性的高级使用及自定义验证实现

    好久没写博客了,今天在百忙之中抽空来写篇文章,记录一下最近深入学习Attribute特性的笔记及心得.~~ 一.什么是特性? 特性(Attribute)是用于在运行时传递程序中各种元素(比如类.方法. ...

  8. Asp.net MVC验证那些事(4)-- 自定义验证特性

    在项目的实际使用中,MVC默认提供的Validation Attribute往往不够用,难以应付现实中复杂多变的验证需求.比如, 在注册用户的过程中,往往需要用户勾选”免责声明”,这个checkbox ...

  9. SAE微信公众号PHP SDK, token一直验证失败

    用的是SAE,创建的是微信公众号PHP SDK框架,里面example文件夹下有server.php用来验证token的.但是问题来了,无论我怎么输入URL和token,一直告诉我token验证失败. ...

随机推荐

  1. innerText兼容问题处理

    IE.Safari.Opera和Chrome支持innerText属性.低版本的火狐浏览器不支持,但支持作用类似的textContent属性.textContent是DOM3级规定的一个属性,而且也得 ...

  2. Python深入类和对象

    一. 鸭子类型和多态 1.什么是鸭子类型: 在程序设计中,鸭子类型(英语:Duck typing)是动态类型和某些静态语言的一种对象推断风格."鸭子类型"像多态一样工作,但是没有继 ...

  3. 如何使用Action.Invoke()触发一个Storyboard

    一般在我们的项目中,最好是将Storyboard放在前台,然后设置Storyboard的x:key值,通过我们的TryFindResource来查找到当前的Storyboard来启动Stroyboar ...

  4. Apache ab 单测 分布式

    使用synchronized 处理并发 缺点:无法做到细粒度控制 只适合单点的情况 使用Redis作为分布式锁 setnx命令 设计模式 :使用 !setnx 加锁 getset命令

  5. Js返回上一页,刷新页面,定时刷新,改变地址栏 等常用实用技巧

    1. Javascript 返回上一页history.go(-1), 返回两个页面: history.go(-2); 2. history.back(). 3. window.history.forw ...

  6. NotBacon

    What's It Do? The application consists of two components: A Custom Vision Service project that allow ...

  7. Nginx 如何增大nginx使用cpu有效时长

    L:121 我们使用 这个命令查看nginx的cpu时间片切换 pidstat - 首先要知道问题: NICE 表示友好 也就是会让出时间切片 所以我们会将静态优先级设置比较低 让他很不友好 Prio ...

  8. Android系统启动概要

    注:Java系统服务与本地系统服务标注反了 1.Linux内核 Android系统启动时,首先通过BootLoader(系统加载器)加载Linux内核,在Linux加载启动时,首先初始化内核,再调用i ...

  9. Qt 使用openGL 渲染NV12格式的视频

    直接上代码 Nv12Render.h #ifndef NV12RENDER_H #define NV12RENDER_H #include <QOpenGLFunctions> #incl ...

  10. Codeforces1101G (Zero XOR Subset)-less 【线性基】【贪心】

    题目分析: 考虑到这是一个区间的异或问题,不妨求出前缀和,令$sum[i] = Xor_{j=1}^{i}a[j]$. 对于区间$[l,r]$的异或结果,等于$sum[r] \oplus sum[l- ...