public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user;
            DataBaseEntities db = new DataBaseEntities();
            if (context.UserName.First().ToString() == UtilityHelper.ConstTokenPrefix.MobilePassword )
            {
                user = await userManager.FindAsync(db.AspNetUsers.Single(u => u.MyMobilePhone == context.UserName.Substring(1)).UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "手机号码或密码不正确。");
                }
            }else
            {
               // user = await userManager.FindAsync(context.UserName, context.Password);
                user = null;
            }

           

            if (user == null)
            {
                context.SetError("invalid_grant", "用户名或密码不正确。");
               
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public IHttpActionResult SMSSend(string m)
        {
            if (UtilityHelper.ConstVar.testAccount.Any(u=>u == m))
            {
                return Json(new
                {
                    Code = 10000,
                    Detail = new { }
                });
            }
            if (!UtilityHelper.IsMobilePhone(m))
            {
                return Json(new
                {
                    Code = 1,
                    Message = "手机格式不正确"
                });
            }

            Random ran = new Random();
            int RandKey = ran.Next(1000, 9999);

            try
            {

                string mobile = m,
                message = "验证码:" + RandKey.ToString() + " ,两分钟内有效【活动邮】",
                username = ConfigurationManager.AppSettings["SMSUsername"],
                password = ConfigurationManager.AppSettings["SMSKey"],
                url = ConfigurationManager.AppSettings["SMSUrl"];
                byte[] byteArray = Encoding.UTF8.GetBytes("mobile=" + mobile + "&message=" + message);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(username + ":" + password));
                webRequest.Headers.Add("Authorization", auth);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = byteArray.Length;

                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string Message = php.ReadToEnd();
            }catch
            {
                return Json(new
                {
                    Code = 1,
                    Message = "验证码服务器有误"
                });
            }

            DataBaseEntities db = new DataBaseEntities();

            var verify = new cm_SMS_Verify
            {
                Id = Guid.NewGuid().ToString(),
                Code = RandKey,
                CreateDate = DateTime.Now,
                Mobile = m
            };

            db.cm_SMS_Verify.Add(verify);
            db.SaveChanges();

            return Json(new
            {
                Code = 10000,
                Detail = new
                {
                }
            });
        }
        public async Task<IHttpActionResult> Register([FromBody] DM_Register model)
        {
            if (!UtilityHelper.VerifyMobileCode(model.Mobile, model.Code, true))
            {
                return Json(new { Code = 1, Message = "验证码错误或已经失效" });
            }
            DataBaseEntities db = new DataBaseEntities();
            //判断该手机号是否可以注册

            //

            string Id = Guid.NewGuid().ToString();
            var user = new ApplicationUser()
            {
                Id = Id,
                UserName = Id,
                MyMobilePhone = model.Mobile,
                RegisterTime = UtilityHelper.getNow(),
                EmailConfirmed = false,
                PhoneNumberConfirmed = false,
                AccessFailedCount = 0,
                LockoutEnabled = true,
                Sex = 2,  //表示没有性别认定
                Portrait = UtilityHelper.ConstVar.DefaultPortrait
            };
            IdentityResult result = await Request.GetOwinContext().GetUserManager<ApplicationUserManager>().CreateAsync(user, model.Password);
            if (!result.Succeeded)
            {
                //注册不成功
                return Json(new { Code = 1, Message = "注册不成功" });
            }
            else
            {
                //注册成功
                #region 完成一些初始化工作

                #endregion
            }

            string grant_type = "password";
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "grant_type=" + grant_type;
            postData += ("&password="******"&username="******"POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Get response
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(content);
            string username = json["userName"].ToString();
            //   var myuser = db.AspNetUsers_Org.Include("AspNetUsers").Single(u => u.AspNetUsers.UserName == username);

            return Json(new
            {
                Code = 10000,
                Detail = new
                {
                    token = json["access_token"].ToString(),
                    IsValid = true,
                    expired = json[".expires"].ToString(),
                    //NickName = myuser.AspNetUsers.NickName,
                    //UserName = myuser.AspNetUsers.UserName,
                    //Portrait = myuser.AspNetUsers.Portrait
                }
            });
        }
        public async Task<IHttpActionResult> Login([FromBody] DM_Login model)
        {
            DataBaseEntities db = new DataBaseEntities();
            string grant_type = "password";
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "grant_type=" + grant_type;
            postData += ("&password="******"&username="******"POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Get response
            HttpWebResponse myResponse = null;
            
            try
            {
                myResponse = (HttpWebResponse) myRequest.GetResponse();
            }catch(WebException ex)
            {
                if (ex.Message.Contains("400"))
                {
                    return Json(new
                    {
                        Code = 1,
                        Message = "手机号码或密码错误"
                    });
                }else
                {
                    return Json(new  {
                        Code = 1,
                        Message = "网络访问错误"
                    });
                }
            }
             
   
            
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(content);

            return Json(new
            {
                Code = 10000,
                Detail = new
                {
                    token = json["access_token"].ToString(),
                    IsValid = true,
                    expired = json[".expires"].ToString()
                }

            });


        }