context.Request.User在OWIN OAuthAuthorizationServerProvider中为null

Jam*_*nes 5 iis oauth owin asp.net-web-api2

我正在尝试使用OWIN为我的本地Intranet上的Web API v2端点实现OAuth.API使用内置Windows身份验证托管在IIS中.简而言之,这就是我想要发生的事情.

当我在令牌处要求令牌时

  1. 将WindowsPrincipal从OWIN上下文中拉出来

  2. 使用WindowsPrincipal中的SID在SQL表中查找此用户的某些角色.

  3. 创建一个存储用户名和角色的新ClaimsIdentity

  4. 把它变成我发送bak的Json Web Token(JWT)

当我使用我的令牌从我的API请求资源时

  1. 将JWT Bearer标记转换回ClaimsIdentity

  2. 使用ClaimsIdentity按角色授权对资源的请求

  3. 这样我就不必在每个请求上对用户角色进行数据库查找.它刚刚融入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());

}
Run Code Online (Sandbox Code Playgroud)

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.为什么在这种情况下它为空?难道我做错了什么?

Tra*_*her 14

交换UseOAuthAuthorizationServer和UseOAuthBearerAuthentication的顺序.使用OAuthBearerAuthentication调用UseStageMarker(PipelineStage.Authenticate);使其(以及之前的所有内容)在ASP.NET管道中运行.在Authenticate阶段运行时,User为null.