我自己托管WebApi,配置如下:
Visual Studio 2012 / .NET 4.0
public void Configuration(IAppBuilder appBuilder) { var config = new HttpConfiguration(); // authentication config.MessageHandlers.Add(new Shield.PresharedKeyAuthorizer()); // routing config.Routes.MapHttpRoute( name: "Default",routeTemplate: "{controller}/{id}",defaults: new { id = RouteParameter.Optional } ); appBuilder.UseWebApi(config); }
我有一个简单的测试设置,使用以下DelegatingHandler创建一个声明并将其附加到当前线程.
public class PresharedKeyAuthorizer : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,System.Threading.CancellationToken cancellationToken) { var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name,"superstar")); var identity = new ClaimsIdentity(claims,"PresharedKey"); var principal = new ClaimsPrincipal(identity); Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) HttpContext.Current.User = principal; return base.SendAsync(request,cancellationToken); } }
但是,当我打开标有Authorize属性的ApiController时,它不会识别身份验证.
[Authorize] public class FilesController : ApiController { public IEnumerable<string> Get() { return new string[] { "Secure File A","Secure File B" }; } }
删除Authorize属性并设置断点,我可以看到RequestContext.Principal属性确实为空.请求没有授权属性,所以我知道自主托管的设置是正确的,但我必须在认证管道中缺少一些东西.
我不知道允许该声明对Authorize属性有效吗?
使用相同方法的相关答案在IIS:https://stackoverflow.com/a/14872968/118224托管时似乎工作
解决方法
在消息处理程序中,设置这样的主体.
request.GetRequestContext().Principal = principal;
不使用
Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) HttpContext.Current.User = principal;
UPDATE
自从我在.NET 4.0 / 2012 / Web API< 2中工作以来已经有一段时间了.所以我肯定不能回答.但是,OWIN主持人必须在OWIN上下文中设置主体. OwinHttpRequestContext在OWIN上下文中设置Thread.CurrentPrincipal和principal.通过使用request.GetRequestContext().主体,这些细节从你隐藏.为了简短的说明,我相信如果你有一些如何设定OWIN上下文中的主体,这将会奏效.不知道如何从Web API消息处理程序中做到这一点.您可以从OWIN中间件执行此操作.
public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.Routes.MapHttpRoute("default","api/{controller}/{id}"); //config.MessageHandlers.Add(new PresharedKeyAuthorizer()); app.Use((IOwinContext context,Func<Task> next) => { var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name,"PresharedKey"); var principal = new ClaimsPrincipal(identity); context.Request.User = principal; return next.Invoke(); }); app.UseWebApi(config); }