如何修复/ Token请求

时间:2017-12-07 10:03:03

标签: c# asp.net-web-api token asp.net-authorization

课程:初创

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            //enable cors origin requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new ClinicServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }

类:ClinicServerProvider

 public class ClinicServerProvider : OAuthAuthorizationServerProvider
    {
        private readonly BoilerplateDbContext _context;

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            UnitOfWork uow = new UnitOfWork(_context);
            string epass = Crypto.EncryptString(context.Password);
            var user = uow.UserRepository.Get(x => x.Password == epass && x.UserName == context.UserName && x.IsActive==true).FirstOrDefault();
// Other custom code here.

}
}

在上面的方法.. 我的 context.Password 总是来自null
 enter image description here
有谁知道是什么原因?

3 个答案:

答案 0 :(得分:0)

在方法GrantResourceOwnerCredentials上,在验证用户名密码后添加声明后,您需要添加此声明:

MongoError: no primary found in replicaset

答案 1 :(得分:0)

一个迟来的答案,但万一将来有人可能遇到类似的情况...

您的请求数据中的x-www-form-urlencoded键名必须命名为usernamepassword

如果键名使用不同的名称,则context.UserNamecontext.Password将始终产生null值。

答案 2 :(得分:0)

我遇到了与您类似的问题,但我的问题是 context.UserName = ""。我努力检查我的代码,但我没有发现任何错误。

我测试了 Postman 的请求。我在 Postman 的参数中找到了问题的原因。 解决办法是删除参数username,重新创建。

Parameter on Postman

我认为此解决方案可能会对您有所帮助。