Web API之认证(Authentication)两种实现方式

移动开发
对于所谓的认证说到底就是安全问题,在Web API中有多种方式来实现安全,【accepted】方式来处理基于IIS的安全(通过上节提到的WindowsIdentity依赖于HttpContext和IIS认证)或者在Web API里通过使用Web API中的消息处理机制,但是如果我们想应用程序运行在IIS之外此时Windows Idenitity这一方式似乎就不太可能了,同时在Web API中本身就未提供如何处理认证的直接方式,我们不得不自定义来实现认证功能,同时这也是我们所推荐的方式,自己动手,丰衣足食。

序言

对于所谓的认证说到底就是安全问题,在Web API中有多种方式来实现安全,【accepted】方式来处理基于IIS的安全(通过上节提到的WindowsIdentity依赖于HttpContext和IIS认证)或者在Web API里通过使用Web API中的消息处理机制,但是如果我们想应用程序运行在IIS之外此时Windows Idenitity这一方式似乎就不太可能了,同时在Web API中本身就未提供如何处理认证的直接方式,我们不得不自定义来实现认证功能,同时这也是我们所推荐的方式,自己动手,丰衣足食。
温馨提示:下面实现方法皆基于基础认证,若不熟悉Http协议中的Basic基础认证,请先参看此篇文章【园友海鸟-介绍Basic基础认证和Diges摘要认证】。


无论何种方式,对于我们的应用程序我们都需要在业务层使用基于凭证的用户认证,因为是客户端一方的需求,所以客户端需要明确基础验证,基础认证(Basic)非常简单并且支持任何Web客户端,但是基础验证的缺点是不安全,通过使用SSL则可以进行加密就可以在一定程度上保证了安全,如果是对于一般的应用程序通过基础认证只是进行编码而未加密也可以说是安全的。我们还是看看上一节所给图片

通过上述图片的粗略信息我们可以看出在请求到Action方法之间要经过Web API消息处理管道,在请求到目标元素之前要经过HttpMessageHandler和认证过滤器,所以我们可以通过这两者来自定义实现认证。下面我们一一来看。
基于Web API的认证过滤器(AuthorizationFilterAttribute)实现认证
***步

我们自定义一个认证身份(用户名和密码)的类,那么此类必须也就要继承于 GenericIdentity ,既然是基于基础验证,那么类型当然也就是Basic了。

  1. public class BasicAuthenticationIdentity : GenericIdentity 
  2. public string Password { get; set; } 
  3. public BasicAuthenticationIdentity(string name, string password) 
  4. : base(name, "Basic"
  5. this.Password = password; 


第二步

我们要自定义一个认证过滤器特性,并继承 AuthorizationFilterAttribute ,此时会变成如下:

  1. public class BasicAuthenticationFilter : AuthorizationFilterAttribute 
  2. public override void OnAuthorization(HttpActionContext actionContext) 
  3. {} 

那么在这个重写的方法我们应该写什么呢?我们慢慢来分析!请往下看。

解析请求报文头

首先对于客户单发送过来的请求我们肯定是需要获得请求报头,然后解析请求报头中的Authorization,若此时其参数为空,我们将返回到客户端,并发起质询。

 

  1.  string authParameter = null
  2.  
  3. var authValue = actionContext.Request.Headers.Authorization; //actionContext:Action方法请求上下文 
  4. if (authValue != null && authValue.Scheme == "Basic"
  5. authParameter = authValue.Parameter; //authparameter:获取请求中经过Base64编码的(用户:密码) 
  6.  
  7. if (string.IsNullOrEmpty(authParameter)) 
  8.  
  9. return null
次之,若此时认证中的参数不为空并开始对其进行编码,并返回一个BasicAuthenticationIdentity对象,若此时对象为空,则同样返回到客户端,并发起质询
  1. uthParameter = Encoding.Default.GetString(Convert.FromBase64String(authParameter)); //对编码的参数进行解码 
  2.  
  3. var authToken = authParameter.Split(':'); //解码后的参数格式为(用户名:密码)将其进行分割 
  4. if (authToken.Length < 2
  5. return null
  6.  
  7. return new BasicAuthenticationIdentity(authToken[0], authToken[1]); //将分割的用户名和密码传递给此类构造函数进行初始化 


***,我们将上述两者封装为一个ParseHeader方法以便进行调用

  1.  public virtual BasicAuthenticationIdentity ParseHeader(HttpActionContext actionContext) 
  2. string authParameter = null
  3.  
  4. var authValue = actionContext.Request.Headers.Authorization; 
  5. if (authValue != null && authValue.Scheme == "Basic"
  6. authParameter = authValue.Parameter; 
  7.  
  8. if (string.IsNullOrEmpty(authParameter)) 
  9.  
  10. return null
  11.  
  12. authParameter = Encoding.Default.GetString(Convert.FromBase64String(authParameter)); 
  13.  
  14. var authToken = authParameter.Split(':'); 
  15. if (authToken.Length < 2
  16. return null
  17.  
  18. return new BasicAuthenticationIdentity(authToken[0], authToken[1]); 

接下来我们将认证未通过而需要发起认证质询,我们将其封装为一个方法Challenge

  1. void Challenge(HttpActionContext actionContext) 
  2. var host = actionContext.Request.RequestUri.DnsSafeHost; 
  3. actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 
  4. actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host)); 
  5.  

定义一个方法便于对用户名和密码进行校验,并将其修饰为虚方法,以免后续要添加其他有关用户数

  1.  public virtual bool OnAuthorize(string userName, string userPassword, HttpActionContext actionContext) 
  2. if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(userPassword)) 
  3.  
  4. return false
  5. else 
  6. return true
  7.  

在认证成功后将认证身份设置给当前线程中Principal属性

  1. ar principal = new GenericPrincipal(identity, null); 
  2.  
  3. Thread.CurrentPrincipal = principal; 
  4.  
  5. //下面是针对ASP.NET而设置 
  6. //if (HttpContext.Current != null) 
  7. // HttpContext.Current.User = principal; 


第三步

一切已经就绪,此时在重写方法中进行相应的调用即可,如下:

  1.  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] 
  2. public class BasicAuthenticationFilter : AuthorizationFilterAttribute 
  3. public override void OnAuthorization(HttpActionContext actionContext) 
  4. var userIdentity = ParseHeader(actionContext); 
  5. if (userIdentity == null
  6. Challenge(actionContext); 
  7. return
  8.  
  9. if (!OnAuthorize(userIdentity.Name, userIdentity.Password, actionContext)) 
  10. Challenge(actionContext); 
  11. return
  12.  
  13. var principal = new GenericPrincipal(userIdentity, null); 
  14.  
  15. Thread.CurrentPrincipal = principal; 
  16.  
  17. base.OnAuthorization(actionContext); 

 #p#


第四步

自定义 CustomBasicAuthenticationFilter 并继承于 BasicAuthenticationFilter ,重写其虚方法。

  1.  public class CustomBasicAuthenticationFilter : BasicAuthenticationFilter 
  2. public override bool OnAuthorize(string userName, string userPassword, HttpActionContext actionContext) 
  3. if (userName == "xpy0928" && userPassword == "cnblogs"
  4.  
  5. return true
  6. else 
  7. return false
  8.  


***一步

注册自定义认证特性并进行调用

  1.  config.Filters.Add(new CustomBasicAuthenticationFilter()); 
  2.  
  3. [CustomBasicAuthenticationFilter] 
  4. public class ProductController : ApiController 
  5. {....} 

至此对于其认证方式就已经完全实现,接下来我们通过【搜狗浏览器】来验收我们的成果。

看到如下认证其用户名和密码的图片,我们知道我们成功了一半

我们点击取消,观察是否返回401并添加质询头即WWW-Authenticate,如我们所料

我们输入正确的用户名和密码再试试看,结果认证成功,如下:

基于Web API的消息处理管道(HttpMessageHandler)实现认证

我们知道HttpMessageHandler是Web API中请求-响应中的消息处理管道的重要角色,但是真正实现管道串联的是DelegatingHandler,若你不懂Web API消息管道,请参考前面系列文章,所以我们可以自定义管道来进行拦截通过继承DelegatingHandler。下面我们一步步来实现基于此管道的认证。
***步

和***种方法一致不再叙述。
第二步

这一步当然是自定义管道进行处理并继承DelegatingHandler,重载在此类中的SendAsync方法,通过获得其请求并处理从而进行响应,若不懂此类中的具体实现,请参看前面系列文章。

同样是我们需要根据请求来解析请求报头,我们依然需要解析报头方法,但是需要稍作修改

 

  1.  public virtual BasicAuthenticationIdentity ParseHeader(HttpRequestMessage requestMessage) 
  2. string authParameter = null
  3.  
  4. var authValue = requestMessage.Headers.Authorization; 
  5. if (authValue != null && authValue.Scheme == "Basic"
  6. authParameter = authValue.Parameter; 
  7.  
  8. if (string.IsNullOrEmpty(authParameter)) 
  9.  
  10. return null
  11.  
  12. authParameter = Encoding.Default.GetString(Convert.FromBase64String(authParameter)); 
  13.  
  14. var authToken = authParameter.Split(':'); 
  15. if (authToken.Length < 2
  16. return null
  17.  
  18. return new BasicAuthenticationIdentity(authToken[0], authToken[1]); 

此时质询也得作相应的修改,因为此时不再是依赖于Action请求上下文,而是请求(HttpRequestMessage)和响应(HttpResponseMessage)

 

  1.  void Challenge(HttpRequestMessage request,HttpResponseMessage response) 
  2. var host = request.RequestUri.DnsSafeHost; 
  3.  
  4. response.Headers.Add(authenticationHeader, string.Format("Basic realm=\"{0}\"", host)); 
  5.  
  6. }

最终继承自DelegatingHandler的代码如

 

  1.  public class BasicAuthenticationHandler : DelegatingHandler 
  2. private const string authenticationHeader = "WWW-Authenticate"
  3. protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
  4. var crendentials = ParseHeader(request); 
  5.  
  6. if (crendentials != null
  7. var identity = new BasicAuthenticationIdentity(crendentials.Name, crendentials.Password); 
  8.  
  9. var principal = new GenericPrincipal(identity, null); 
  10.  
  11. Thread.CurrentPrincipal = principal; 
  12.  
  13. //针对于ASP.NET设置 
  14. //if (HttpContext.Current != null) 
  15. // HttpContext.Current.User = principal; 
  16.  
  17. return base.SendAsync(request, cancellationToken).ContinueWith(task => { 
  18. var response = task.Result; 
  19. if (crendentials == null && response.StatusCode == HttpStatusCode.Unauthorized) 
  20. Challenge(request, response); 
  21.  
  22. return response; 
  23. }); 
  24.  
  25.  
  26. void Challenge(HttpRequestMessage request,HttpResponseMessage response) 
  27. var host = request.RequestUri.DnsSafeHost; 
  28.  
  29. response.Headers.Add(authenticationHeader, string.Format("Basic realm=\"{0}\"", host)); 
  30.  
  31.  
  32. public virtual BasicAuthenticationIdentity ParseHeader(HttpRequestMessage requestMessage) 
  33. string authParameter = null
  34.  
  35. var authValue = requestMessage.Headers.Authorization; 
  36. if (authValue != null && authValue.Scheme == "Basic"
  37. authParameter = authValue.Parameter; 
  38.  
  39. if (string.IsNullOrEmpty(authParameter)) 
  40.  
  41. return null
  42.  
  43. authParameter = Encoding.Default.GetString(Convert.FromBase64String(authParameter)); 
  44.  
  45. var authToken = authParameter.Split(':'); 
  46. if (authToken.Length < 2
  47. return null
  48.  
  49. return new BasicAuthenticationIdentity(authToken[0], authToken[1]); 

#p#
第三步

上述我们自定义的BasicAuthenticationFilter此时就得继承 AuthorizeAttribute 该特性也是继承于上述的 AuthorizationFilterAttribute ,我们需要利用AuthorizeAttribute中的 IsAuthorized 方法来验证当前线程中的Principal是否已经被授权。
 

 

  1.  public class BasicAuthenticationFilter : AuthorizeAttribute 
  2. protected override bool IsAuthorized(HttpActionContext actionContext) 
  3.  
  4. var identity = Thread.CurrentPrincipal.Identity; 
  5. if (identity != null && HttpContext.Current != null
  6. identity = HttpContext.Current.User.Identity; 
  7.  
  8. if (identity != null && identity.IsAuthenticated) 
  9.  
  10. var basicAuthIdentity = identity as BasicAuthenticationIdentity; 
  11.  
  12. //可以添加其他需要的业务逻辑验证代码 
  13. if (basicAuthIdentity.Name == "xpy0928" && basicAuthIdentity.Password == "cnblogs"
  14. return true
  15.  
  16. return false
  17.  

通过 IsAuthorized 方法返回值来看,若为false,则返回401状态码,此时会触发 BasicAuthenticationHandler 中的质询,并且此方法里面主要是我们需要添加认证用户的业务逻辑代码。同时我们也说过我们***种方法自定义实现的过滤器特性是 AuthorizationFilterAttribute (如果我们有更多逻辑使用这个特性是个不错的选择),而在这里是 AuthorizeAttribute (对于验证用户并且返回bool值使用此过滤器特性是个不错的选择)。
第四步

注册自定义管道以及认证过滤器特性

  1. config.MessageHandlers.Add(new BasicAuthenticationHandler()); 
  2. config.Filters.Add(new BasicAuthenticationFilter()); 

***一步

[BasicAuthenticationFilter]
public class ProductController : ApiController
{.....}

下面我们通过【360极速浏览器】来验收成果。点击按钮直接请求控制器

接下来取消,是否返回401

至此***结束。
总结
用认证特性(AuthorizationFilterAttribute)还是HttpMessageHandler实现认证,这是一个问题?
通过比较这二者的实现操作在实现方式上明显有极大的不同,个人觉得用AuthorizationFilterAttribute来实现认证是更加简单并且紧凑,因为实现的每一处都在每一个地方,在大多数实现自定义登陆的场景下,对于用过滤器如此紧凑的业务逻辑用这个更加高效, 用HttpMessageHandler的优点是全局应用且是Web API消息处理管道的一部分,如果对于不同的部分要用不同的认证那么用HttpMessageHandler效果更好,但是此时你需要自定义一个过滤器,尤其是当MessageHandler对于一个认证需要一个过滤器的时候。所以综上所述,根据不同的应用场景我们应该选择对应的方式来实现认证。

责任编辑:chenqingxiang 来源: xpy0928的博客
相关推荐

2023-03-29 13:06:36

2010-07-14 10:30:26

Perl多线程

2011-03-03 10:26:04

Pureftpd

2022-06-08 15:12:34

前端前端截图

2021-12-08 10:47:35

RabbitMQ 实现延迟

2009-04-03 09:00:20

SQL Server2005用户

2010-09-28 15:12:27

Javascript

2024-01-09 09:09:45

RESTGraphQL

2009-06-15 15:02:48

Spring定时器

2010-09-07 11:09:59

2020-05-11 13:03:03

SR-TEIP路由器

2023-05-31 19:10:31

2010-07-13 14:54:15

Perl面向对象编程

2010-02-02 14:32:32

Python线程编程

2010-10-21 16:24:18

sql server升

2009-06-25 13:43:00

Buffalo AJA

2021-05-27 10:57:01

TCP定时器网络协议

2021-10-19 10:56:00

插件工程方式

2010-08-06 09:38:11

Flex读取XML

2010-04-20 15:32:20

主控负载均衡
点赞
收藏

51CTO技术栈公众号