Web Api 2 认证与授权 2

时间:2024-01-13 19:46:08

HTTP Message Handler

Web Api 2 认证与授权 中讲解了几种实现机制,本篇就详细讲解 Message Handler 的实现方式

关于 Message Handler 在 request 到 response 过程所处于的位置,可以参考这里 HTTP Message Handlers

Authentication Message Handler

先看一段实现的代码,然后再做讲解,完整代码可以在 Github 上参考,WebApi2.Authentication

 using System;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
// WebPrint.Framework reference https://github.com/LeafDuan/WebPrint/tree/master/WebPrint.Framework
using WebPrint.Framework; namespace Server.Helper
{
// references
// http://www.codeproject.com/Articles/630986/Cross-Platform-Authentication-With-ASP-NET-Web-API
// http://dgandalf.github.io/WebApiTokenAuthBootstrap/
public class AuthenticationMessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request.Headers.Authorization == null)
{
var reply = request.CreateResponse(HttpStatusCode.Unauthorized, "Missing authorization token."); return Task.FromResult(reply);
} try
{
var encryptedToken = request.Headers.Authorization.Parameter;
var token = Token.Decrypt(encryptedToken);
//bool isValidUser
var isIpMathes = token.ClientIp.EqualTo(request.GetClinetIp()); if (!isIpMathes)
{
var reply = request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid authorization token");
return Task.FromResult(reply);
} var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, token.UserId.ToString())
}, "Basic")); // authorize attribute
request.GetRequestContext().Principal = principal;
}
catch (Exception ex)
{
var reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
return Task.FromResult(reply);
} return base.SendAsync(request, cancellationToken);
}
}
}

实现也是很简单,通过继承 DelegatingHandler 重写 SendAsync 方法实现,整个流程需要的步骤如下:

1 登录,通过 api/auth 接收登录信息,验证后生成一个 token

2 每次请求判断  request.Headers.Authorization 参数,看是否携带 token (Http Client 将步骤 1 中的 token 设置到 request.Headers.Authorization)

3 解析 token,设置请求上下文的 Principal 用于 Authorize 属性使用

基本过程就差不多这三部曲,其中关于 token 的验证,如是否超时,是否重复,可自行想办法去实现

Web Api Config

大家都知道 Message Handler 在 pipeline 里是在 controller 之前运行,因此请求所有的 Api Controller 都会先执行 handler,因此针对登录,需要给予额外的照顾,允许匿名访问,实现方法:handler 可以是全局的,也可以是 per router 的,因此此处通过后一种方式实现:

 using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using Newtonsoft.Json;
using Server.Helper; namespace Server
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "Authentication",
routeTemplate: "api/auth",
defaults: new {controller = "account"}
); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional},
constraints: null,
handler: new AuthenticationMessageHandler {InnerHandler = new HttpControllerDispatcher(config)}
); var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
jsonFormatter.SerializerSettings.ContractResolver = new NHibernateContractResolver();
}
}
}

总结

最近匆匆忙忙使用托管在 Owin Self Host 上的 Web Api 2,遇到问题颇多,很多也是匆匆忙忙解决的,这里也就匆匆忙忙做一个分享。