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

How do I check an OWIN request before HttpContext.Current.User.Identity is set?

我的 webapi2 站点有一个 OWIN 设置,它使用 Bearer 令牌。一切正常,但我现在需要实施安全检查。

这是我需要完成的事情

  1. 创建存储 RemoteIpAddress 的身份时添加新声明。这部分我已经想通了。
  2. 检查每个使用 bearer 令牌的传入请求,并检查当前 ip 地址是否与令牌中设置的地址匹配。不确定在哪里做这个最好。

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

是否可以使用OAuthAuthorizationServerProvider检查OWIN请求,如果不满足则取消认证?我真的不知道对 verify/decrypt 不记名令牌进行实际检查的位置,如果可能的话,我想要一个钩子或覆盖来接入。

您可以创建一个 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