如何在HttpContext.Current.User.Identity设置之前检查OWIN请求?

问题描述:

我有一个使用持票人令牌的webapi2网站的OWIN设置。一切正常,但我现在需要实施安全检查。如何在HttpContext.Current.User.Identity设置之前检查OWIN请求?

这就是我需要完成

  1. 创建存储RemoteIpAddress的身份时,添加了新的要求。这部分我已经找到了。
  2. 检查使用承载令牌的每个入局请求,并检查当前IP地址是否与令牌中设置的地址匹配。不知道最好的地方在哪里做这件事。

我打算把自己的支票放在自定义的AuthorizeAttribute中,但它感觉不合适。

是否可以使用OAuthAuthorizationServerProvider检查OWIN请求,并在条件不满足的情况下取消认证?我真的不知道在哪里进行实际检查以验证/解密不记名令牌,并且如果可能的话,会想要挂钩或覆盖。

您可以创建一个owin中间件来检查IP地址,作为链中的第一步。 把它作为第一个中间件被连接到IAppBuilder,以确保它会链的其他部分之前调用

public class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     app.Use((context, next) => 
     { 
      if (!IsIpAdressOk(context.Request)) //if the ip is invalid, stop the process and just return a response to the client 
      { 
       return context.Response.WriteAsync("Get lost!"); 
      } 
      return Next.Invoke(context); //if the ip is correct then continue to the next middleware 
     }); 

     ...add OAuthAuthorizationServerProvider and the rest here 
    } 
} 

大博客约Owin中间件here

+1

真棒,正是我一直在寻找。谢谢! – Matt