使用 ASP.NET Web API 2 和 Owin 抛出 401 未授权的基于令牌的身份验证

Token Based Authentication using ASP.NET Web API 2 and Owin throws 401 unauthorized

我已经使用 Taiseer Joudeh 中的指南创建了 OAuth 身份验证。我已经创建了一个端点/token 来进行身份验证。它有效,我收到了这样的结果。

{
  "access_token": "dhBvPjsHUoIs6k8NDsXfROpTq63qlww_7Bifl0LOzIxhZnngld0QCU-x4q4Qa7xWhhIQeQbbK6gYu_hLIYfUbsFMsdXwqlOqAYabJHNNsnJPMMHNADb-KCQznPQy7-waaqKMCVH1HPqx4L30sXlX0L8MbjtrtkX9-jxHaWdPapqYA9lU4Ai2-Z5-zXxoriFDL-SvxrUnBTDQMnRxOH_oEyclUngzW-is543TtJ0bysQ",
  "token_type": "bearer",
  "expires_in": 86399
}

但是,如果我在下一次调用具有 AuthorizeAttribute 的点的 header 中使用访问令牌,我总是会收到未经授权的错误。此外,如果我查看当前线程的 CurrentPrincipal 中的内容,它始终是 GenericPrincipal。

我的启动 class 看起来像这样(看起来与指南中的相似)

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            HttpConfiguration config = new HttpConfiguration();
            IContainer container = AutoFacConfig.Register(config, app);

            ConfigureOAuth(app, container);

            WebApiConfig.Register(config);
            AutoMapperConfig.Register();

            app.UseWebApi(config);
        }
        public void ConfigureOAuth(IAppBuilder app, IContainer container)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = container.Resolve<IOAuthAuthorizationServerProvider>()                
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }

    }

而OauthServiceprovider是这样的:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        private readonly IUserBl userBl;


        public SimpleAuthorizationServerProvider(IUserBl userBl)
        {
            this.userBl = userBl;
        }

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            UserDto user = Mapper.Map<UserDto>(userBl.Login(context.UserName, context.Password));

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
    }

唯一的区别是我使用的是 owin 的第 3 版,而不是指南中的第 2 版。是否有一些重大更改破坏了我的代码?

编辑 1:

我正在使用 Autofac 解析接口 IOAuthAuthorizationServerProvider:

builder.RegisterType<SimpleAuthorizationServerProvider>()
                .As<IOAuthAuthorizationServerProvider>()
                .PropertiesAutowired() 
                .SingleInstance();

FOA,您似乎没有在 ConfigureOAuth() 方法中使用 SimpleAuthorizationServerProvider class。

因此,请将代码更改为:

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() {

            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider(),
        };

然后请评论发生了什么。

这个答案解决了我的问题

更改 GrantResourceOwnerCredentials 方法以解析我的用户 class:

var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
var userBl = autofacLifetimeScope.Resolve<IUserBl>();

而不是使用autofac的注入 感谢@taiseer joudeh 提示查看 Autofac