您好,我已经构建了一个授权处理程序来拦截我的 MVC.NET v4 应用程序的所有请求(使用 .NET 4.5)。
处理程序在 Global.asax.cs 和 WebAPIConfig.cs 中注册,用于全局和基于路径的路由配置,我已经完成了 ASP.NET Web API Security book py Apress 中详述的所有步骤。
为 MVC.NET Web 应用程序注册 Auth 处理程序的正确方法是什么?
WebAPIConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new AuthHandler()
);
config.MessageHandlers.Add(new AuthHandler());
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
}
}
AuthHandler.cs
public class AuthHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
var claims = new List<Claim>() {new Claim(ClaimTypes.Name, "ghoil")};
var id = new ClaimsIdentity(claims, "dummy");
var principal = new ClaimsPrincipal(new[] { id });
var config = new IdentityConfiguration();
var newPrincipal = config.ClaimsAuthenticationManager.Authenticate(request.RequestUri.ToString(), principal);
Thread.CurrentPrincipal = newPrincipal;
if (HttpContext.Current != null)
HttpContext.Current.User = newPrincipal;
return await base.SendAsync(request, cancellationToken);
}
}