【问题标题】:How do I check an OWIN request before HttpContext.Current.User.Identity is set?如何在设置 HttpContext.Current.User.Identity 之前检查 OWIN 请求?
【发布时间】:2017-11-25 01:56:07
【问题描述】:
我有一个使用 Bearer 令牌的 webapi2 站点的 OWIN 设置。一切正常,但我现在需要实施安全检查。
这是我需要完成的事情
- 在创建存储 RemoteIpAddress 的身份时添加新声明。这部分我已经想通了。
- 检查每个使用bearer令牌的传入请求,并检查当前IP地址是否与令牌中设置的匹配。不确定在哪里进行此操作的最佳位置。
我打算在自定义 AuthorizeAttribute 中进行检查,但感觉不合适。
是否可以使用 OAuthAuthorizationServerProvider 检查 OWIN 请求,如果不满足条件则取消身份验证?我真的不知道实际检查在哪里进行以验证/解密不记名令牌,并且如果可能的话,想要一个挂钩或覆盖来利用。
【问题讨论】:
标签:
c#
oauth-2.0
asp.net-web-api2
owin
【解决方案1】:
您可以创建一个 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