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

            using (UserAuthentication OBJ = new UserAuthentication())
            {
                UserModel userResult = new UserModel();
                var       user       = OBJ.ValidateUser(context.UserName, context.Password);
                if (user == "false")
                {
                    ///context.SetError("invalid_grant", "Username or password is incorrect");
                    ///context.SetError("invalid_grant", "Username or password is incorrect");
                    ResponseObject obj = new ResponseObject();
                    obj.ResponseMsg  = "Username or password is incorrect";
                    obj.userId       = context.UserName;
                    obj.ExceptionMsg = "Username or password is incorrect";
                    context.SetCustomError(obj);
                    context.Rejected();
                    return;
                }
                else
                {
                    userResult = IService.GetUserDetailbyName(context.UserName);
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Role, "SuperAdmin"));
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim("UserId", userResult.Id.ToString()));
                identity.AddClaim(new Claim("isNGO", userResult.IsNGO.ToString()));
                identity.AddClaim(new Claim("canEndorse", userResult.CanEndorse.ToString()));
                identity.AddClaim(new Claim("DisplayName", userResult.DisplayName));
                identity.AddClaim(new Claim("isAdmin", userResult.IsAdmin.ToString()));
                identity.AddClaim(new Claim("LastLoginDate", userResult.LastLoginTime.ToString()));

                AuthenticationProperties properties = CreateProperties(context.UserName, userResult.Id.ToString(),
                                                                       userResult.DisplayName.ToString(), userResult.IsNGO.ToString(), userResult.CanEndorse.ToString(),
                                                                       userResult.IsAdmin.ToString(), userResult.LastLoginTime.ToString());

                AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);

                context.Validated(ticket);
                // context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            string function = context.Request + " " + context.Request.Method;

            try
            {
                _Logging.WriteTransactionLog(function, "Token verme işlemi başladı...", Helpers.Messages.ErrorMessageCode.Authorization);

                var appId     = context.OwinContext.Get <string>("as:clientAppID");
                var companyId = context.OwinContext.Get <string>("as:clientCompanyID");

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

                #region Kullanıcı işlemleri
                UserProcess        up  = UserProcess.UserProcessMultiton(connectionHelper);
                CompanyUserProcess cup = CompanyUserProcess.CompanyUserProcessMultiton(connectionHelper);
                CompanyApplicationLicenseProcess calp = CompanyApplicationLicenseProcess.UserTokenProcessMultiton(connectionHelper);
                bool  isSuccess     = true;
                Users user          = null;
                var   licenseResult = calp.FindLicenseByCompanyApplicationFunction(Convert.ToInt32(companyId), Convert.ToInt32(appId));
                if (!licenseResult.Result || licenseResult.Object == null)
                {
                    isSuccess = false;
                    _Logging.WriteTransactionLog(function, "Şirketin uygulama lisans bilgilerine ulaşılamadı.", Helpers.Messages.ErrorMessageCode.UnAuthorized);
                    _Logging.WriteApplicationLog(function, "Şirketin uygulama lisans bilgilerine ulaşılamadı.", Helpers.Messages.ErrorMessageCode.Authorization);
                    context.SetCustomError("Şirketin uygulama lisans bilgilerine ulaşılamadı.");
                }
                else
                {
                    var license = Convert.ToInt32(licenseResult.Object.ApplicationLicenseSize.Decrypt());
                    user = up.UserFindFunction(context.UserName, context.Password).Object;
                    if (user == null)
                    {
                        _Logging.WriteTransactionLog(function, string.Format("Kullanıcı: {0} veya parola yanlış.", context.UserName), Helpers.Messages.ErrorMessageCode.UnAuthorized);
                        _Logging.WriteApplicationLog(function, string.Format("Kullanıcı: {0} veya parola yanlış.", context.UserName), Helpers.Messages.ErrorMessageCode.UnAuthorized);
                        context.SetCustomError("Kullanıcı adı veya parola yanlış.");
                        isSuccess = false;;
                    }
                    else
                    {
                        var userInCompany = cup.CanUseToApplication(user.TabloID, Convert.ToInt32(appId), Convert.ToInt32(companyId));

                        if (!userInCompany.Result)
                        {
                            _Logging.WriteTransactionLog(function, string.Format("{0} kullanıcısının girmek istediği {1} id uygulamasına yetkisi yok.", context.UserName, companyId), Helpers.Messages.ErrorMessageCode.UnAuthorized);
                            _Logging.WriteApplicationLog(function, string.Format("{0} kullanıcısının girmek istediği {1} id uygulamasına yetkisi yok.", context.UserName, companyId), Helpers.Messages.ErrorMessageCode.UnAuthorized);

                            context.SetCustomError("Kullanıcının bu uygulama için yetkisi yok.");
                            isSuccess = false;;
                        }
                        else
                        {
                            if (Constants.Dic.Count >= license)
                            {
                                _Logging.WriteTransactionLog(function, string.Format("{0} id uygulaması için kullanıcı sayısı dolmuş.", appId), Helpers.Messages.ErrorMessageCode.UnAuthorized);
                                _Logging.WriteApplicationLog(function, string.Format("{0} id uygulaması için kullanıcı sayısı dolmuş.", appId), Helpers.Messages.ErrorMessageCode.UnAuthorized);
                                context.SetCustomError("Aktif kulalnıcı sayısı dolmuş.");
                                isSuccess = false;
                            }
                        }
                    }
                }

                #endregion

                if (isSuccess)
                {
                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim("UserID", user.TabloID.ToString()));
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.Role, user.AuthorityGroup.AuthorityName));

                    var props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "AppId", appId
                        },
                        {
                            "CompanyId", companyId
                        },
                        {
                            "Username", user.UserFullName
                        },
                        {
                            "UserId", user.TabloID.ToString()
                        }
                    });
                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);
                    context.Request.Context.Authentication.SignIn(identity);

                    _Logging.WriteTransactionLog(function, string.Format("[Kullanıcı:{0}] [Uygulama No:{1}] [Şirket No:{2}] => Giriş Başarılı.", user.UserFullName, appId, companyId), Helpers.Messages.ErrorMessageCode.Authorization);
                }

                _Logging.WriteTransactionLog(function, "Token verme işlemi tamamlandı.", Helpers.Messages.ErrorMessageCode.Authorization);
                _Logging.Finish(function);
            }
            catch (Exception ex)
            {
                _Logging.WriteApplicationLog(function, ex.Message, Helpers.Messages.ErrorMessageCode.TryCatchMessage);
                context.SetCustomError(ex.Message);
            }
        }