使用ASP.NET Web API 2和Owin的基于令牌的身份验证将未经授权发送401

时间:2016-11-05 15:44:55

标签: .net asp.net-web-api oauth owin autofac

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

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

但是如果我在下一次调用具有AuthorizeAttribute的enpoint的标头中使用访问令牌,我总是会发现一个未经授权的错误。另外,如果我看看当前Thread的CurrentPrincipal中的内容,它总是一个GenericPrincipal。

My Startup类看起来像这样(看起来与指南中的类似)

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);

        }
    }

唯一的区别是我使用的是版本3的owin,而不是像指南一样。是否存在一些破坏我的代码的重大变化?

编辑1:

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

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

2 个答案:

答案 0 :(得分:0)

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

因此,请将代码更改为:

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() {

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

然后请评论会发生什么。

答案 1 :(得分:0)

这个答案解决了我的问题 https://stackoverflow.com/a/36769653/5441093

更改GrantResourceOwnerCredentials方法,以解析我的userbl类:

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

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