web api bearer token总是401

时间:2016-12-18 01:34:25

标签: c# asp.net-web-api oauth owin

我创建了简单的web api应用程序。

启动课程:

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            ConfigureOAuth(app);

            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            config.Filters.Add(new AuthorizeAttribute());

            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new GoodwillAuthorizationServerProvider(),

            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = new OAuthBearerAuthenticationProvider()
            });
        }
    }
}

自定义oauh提供商

public class GoodwillAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        private UnitOfWorkFactory _factory;

        public GoodwillAuthorizationServerProvider()
        {
            _factory = new UnitOfWorkFactory();
        }

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

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            using (var unitOfWork = _factory.Create())
            {
                var user = unitOfWork.UsersRepository.GetUserByName(context.UserName);
                if (!unitOfWork.UsersRepository.ValidateUser(context.UserName, context.Password))
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                var role = unitOfWork.UserRolesRepository.GetById(user.RoleID);


                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Role, role.Name));
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim("partner_id", user.PartnerID.ToString()));
                var principal = new GenericPrincipal(identity, new[] {role.Name});
                Thread.CurrentPrincipal = principal;
                context.Validated(identity);
            }
        }
    }

在IIS Express中它运行良好。 在本地IIS中,它也很有效。 但是当我将它部署在远程服务器(IIS)上时,它只返回令牌,但是对[Authorize] attibute的方法的所有请求都返回401。 我实际上不明白它是怎么可能的,我该怎么做才能配置它。 对任何建议都会非常感激!

0 个答案:

没有答案