建立新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. 前K个高频元素

    给定一个非空的整数数组,返回其中出现频率前 k 高的元素. 示例 1: 输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2: 输入: nums = [1], ...

  2. RabbitMQ基本操作

    更加详细的 链接https://www.cnblogs.com/dwlsxj/p/RabbitMQ.html RabbitMQ基础知识 一.背景 RabbitMQ是一个由erlang开发的AMQP(A ...

  3. CMD & Git Shell & Bash Shell

    CMD & Git Shell & Bash Shell https://mvdan.cc/sh/cmd/shfmt PC

  4. python设计模式第六天【原型模式】

    1.定义 使用原型模式复制的对象与原来对象具有一样的结构和数据,有浅克隆和深克隆 2.应用场景 (1)希望复制原来对象的结构和数据胆步影响原来对象 3.代码实现 #!/usr/bin/env pyth ...

  5. How to remove tag on Github

    git tag -d 22 git push origin :refs/tags/22

  6. spring的作用是减低耦合,从编译器降低,例如不直接通过new方式 而是通过工厂方式获取对象

    spring的作用是减低耦合,从编译器降低,例如不直接通过new方式 而是通过工厂方式获取对象

  7. iOS应用的性能调试

    1.Static Analysis 使用之前先清理一下数据:product-->Clean 可能遇到的问题: a.发现工程中有多个“User-facing text should use loc ...

  8. eclipse添加tomcat服务器

    在网上找资料好辛苦,还不对,自己试了好久,终于成功了 还是一如既往的分享 右键 弄好以后发现如此简单| _ |

  9. android打电话方法(直接拨通)

    新建了CallPhone方法,如下: private void CallPhone() { String number = et_number.getText().toString(); if (Te ...

  10. python中的map函数

    def f(x): return x * x """将一个全是数字的list变成平方形式""" def f2(): ls = [1, 2, ...