我正在尝试使用OWIN为我的本地Intranet上的Web API v2 endpoints 实现OAuth . API使用内置Windows身份验证托管在IIS中 . 简而言之,这就是我想要发生的事情 .
When I ask for my Token at /token
-
将WindowsPrincipal拉出OWIN上下文
-
使用WindowsPrincipal中的SID在SQL表中查找此用户的某些角色 .
-
创建一个存储用户名和角色的新ClaimsIdentity
-
把它变成我发送bak的Json Web Token(JWT)
When I request a resource from my API using my token
-
将JWT Bearer令牌转换回ClaimsIdentity
-
使用ClaimsIdentity按角色授权对资源的请求
-
这样我就不必在每个请求上对用户角色进行数据库查找 . 它刚刚融入JWT .
我想我正确地设置了一切 . 我的Startup.Configuration方法看起来像这样 .
public void Configuration(IAppBuilder app)
{
// token generation
// This is what drives the action when a client connects to the /token route
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
// for demo purposes
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
AccessTokenFormat = GetMyJwtTokenFormat(),
Provider = new MyAuthorizationServerProvider()
});
//// token consumption
app.UseOAuthBearerAuthentication(
new OAuthBearerAuthenticationOptions()
{
Realm = "http://www.ccl.org",
Provider = new OAuthBearerAuthenticationProvider(),
AccessTokenFormat = GetMyJwtTokenFormat()
}
);
app.UseWebApi(WebApiConfig.Register());
}
MyAuthorizationServerProvider看起来像这样......
public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// Since I'm hosting in IIS with Windows Auth enabled
// I'm expecting my WindowsPrincipal to be here, but it's null :(
var windowsPrincipal = context.OwinContext.Request.User.Identity;
// windowsPrincipal is null here. Why?
// Call SQL to get roles for this user
// create the identity with the roles
var id = new ClaimsIdentity(stuff, more stuff);
context.Validated(id);
}
}
我的问题是context.Request.User在这里为null . 我无法进入我的WindowsPrincipal . 如果我创建一些其他虚拟中间件,我可以毫无问题地进入WindowsPrincipal . 为什么在这种情况下它为空?难道我做错了什么?
1 回答
交换UseOAuthAuthorizationServer和UseOAuthBearerAuthentication的顺序 . 使用OAuthBearerAuthentication调用
UseStageMarker(PipelineStage.Authenticate);
使其(以及之前的所有内容)在ASP.NET管道中运行 . 在Authenticate阶段运行时,User为null .