您好,我已经构建了一个授权处理程序,以拦截我的MVC.NET v4应用程序的所有请求(使用.NET 4.5)。
对于全局和基于路径的路由配置,Handler在Global.asax.cs,WebAPIConfig.cs中注册,并且我已经完成了ASP.NET Web API安全性书籍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);
}
}