Beispiel #1
0
        public void Insert(AccessTokenInfo accessTokenInfo)
        {
            var token = TranslateUtils.EncryptStringBySecretKey(StringUtils.Guid());

            var sqlString = $@"INSERT INTO {TableName}
           ({nameof(AccessTokenInfo.Title)}, 
            {nameof(AccessTokenInfo.Token)},
            {nameof(AccessTokenInfo.Scopes)},
            {nameof(AccessTokenInfo.RateLimit)},
            {nameof(AccessTokenInfo.AddDate)},
            {nameof(AccessTokenInfo.UpdatedDate)})
     VALUES
           (@{nameof(AccessTokenInfo.Title)}, 
            @{nameof(AccessTokenInfo.Token)},
            @{nameof(AccessTokenInfo.Scopes)},
            @{nameof(AccessTokenInfo.RateLimit)},
            @{nameof(AccessTokenInfo.AddDate)},
            @{nameof(AccessTokenInfo.UpdatedDate)})";

            IDataParameter[] parameters =
            {
                GetParameter(nameof(accessTokenInfo.Title),       DataType.VarChar,                         200, accessTokenInfo.Title),
                GetParameter(nameof(accessTokenInfo.Token),       DataType.VarChar,                         200, token),
                GetParameter(nameof(accessTokenInfo.Scopes),      DataType.VarChar,                         200, accessTokenInfo.Scopes),
                GetParameter(nameof(accessTokenInfo.RateLimit),   DataType.Integer,  accessTokenInfo.RateLimit),
                GetParameter(nameof(accessTokenInfo.AddDate),     DataType.DateTime, DateTime.Now),
                GetParameter(nameof(accessTokenInfo.UpdatedDate), DataType.DateTime, DateTime.Now)
            };

            ExecuteNonQuery(sqlString, parameters);

            AccessTokenManager.ClearCache();
        }
Beispiel #2
0
        public string GetAccessToken(AccessTokenRequest request)
        {
            if (AccessTokenInfo.Exists(request.AuthorizationId))
            {
                var answer = MessageBox.Show("Den AuthorizationCode som angivits är redan förbrukad. Vill du skicka ändå för att deaktivera denna integration?",
                                             "AccessToken existerar",
                                             MessageBoxButton.YesNo,
                                             MessageBoxImage.Warning,
                                             MessageBoxResult.No);

                if (answer == MessageBoxResult.No)
                {
                    //return "En AccessToken har redan skapats med given AuthorizationCode.";
                    return("Den AuthorizationCode som angivits är redan förbrukad.");
                }
            }

            var accessTokenInfo = AccessTokenInfo.GetAccessToken(request.AuthorizationId, request.ClientSecret);

            if (!accessTokenInfo.HasError)
            {
                var authorizationCodeEdit = AuthorizationCodeEdit.NewAuthorizationCode();
                authorizationCodeEdit.AuthorizationCode = request.AuthorizationId;
                authorizationCodeEdit = authorizationCodeEdit.Save();
            }

            return(accessTokenInfo.AccessToken);
            //return $"Ny Guid: {Guid.NewGuid().ToString()}";
        }
Beispiel #3
0
        public AccessTokenInfo GetAccessTokenInfo(int id)
        {
            AccessTokenInfo accessTokenInfo = null;

            var sqlString = $@"SELECT {nameof(AccessTokenInfo.Id)}, 
                {nameof(AccessTokenInfo.Title)}, 
                {nameof(AccessTokenInfo.Token)},
                {nameof(AccessTokenInfo.AdminName)},
                {nameof(AccessTokenInfo.Scopes)},
                {nameof(AccessTokenInfo.RateLimit)},
                {nameof(AccessTokenInfo.AddDate)},
                {nameof(AccessTokenInfo.UpdatedDate)}
            FROM {TableName} WHERE {nameof(AccessTokenInfo.Id)} = {id}";

            using (var rdr = ExecuteReader(sqlString))
            {
                if (rdr.Read())
                {
                    accessTokenInfo = GetAccessTokenInfo(rdr);
                }
                rdr.Close();
            }

            return(accessTokenInfo);
        }
Beispiel #4
0
        public bool ValidateUserActionAndGenerateUserSession(AuthTokenParameters authTokenParameters, OAuth10aStateManager oAuth10AStateManager)
        {
            TaskTrackerDalForAuth taskTrackerDalForAuth = new TaskTrackerDalForAuth();
            var authClientConfig = taskTrackerDalForAuth.GetClientConfig(authTokenParameters.BaseUrl);

            var JiraApplicationCredentials = new ApplicationCredentials
            {
                ConsumerKey    = authClientConfig.ConsumerKey,
                ConsumerSecret = authClientConfig.ConsumerSecretKey.ToXmlString(true)
            };
            var JiraOAuth1AProvider = new JIRAOAuth1aProvider(authTokenParameters.BaseUrl);
            var processUserResponse = OAuth1aProcess.ProcessUserResponse(JiraOAuth1AProvider, JiraApplicationCredentials,
                                                                         authTokenParameters.RequestUrl, oAuth10AStateManager);

            processUserResponse.Wait();
            AccessTokenInfo accessTokenInfo = new AccessTokenInfo()
            {
                AccessToken       = processUserResponse.Result.AllParameters["oauth_token"],
                AccessTokenSecret = processUserResponse.Result.AllParameters["oauth_token_secret"],
            };

            if (!taskTrackerDalForAuth.SaveUserSession(authTokenParameters.AuthClientConfigId, accessTokenInfo))
            {
                authTokenParameters.AuthClientConfigId = 0;
            }
            return(true);
        }
Beispiel #5
0
        private static AccessTokenInfo GetAccessTokenInfo(IDataRecord rdr)
        {
            if (rdr == null)
            {
                return(null);
            }

            var accessTokenInfo = new AccessTokenInfo();

            var i = 0;

            accessTokenInfo.Id = rdr.IsDBNull(i) ? 0 : rdr.GetInt32(i);
            i++;
            accessTokenInfo.Title = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i);
            i++;
            accessTokenInfo.Token = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i);
            i++;
            accessTokenInfo.AdminName = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i);
            i++;
            accessTokenInfo.Scopes = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i);
            i++;
            accessTokenInfo.RateLimit = rdr.IsDBNull(i) ? 0 : rdr.GetInt32(i);
            i++;
            accessTokenInfo.AddDate = rdr.IsDBNull(i) ? DateTime.Now : rdr.GetDateTime(i);
            i++;
            accessTokenInfo.UpdatedDate = rdr.IsDBNull(i) ? DateTime.Now : rdr.GetDateTime(i);

            return(accessTokenInfo);
        }
Beispiel #6
0
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        private static AccessTokenInfo GetAccessToken()
        {
            DateTime _now = DateTime.Now;

            //有效时间到 从新获取AccessToken
            if (_accessToken == null || _now >= _expTime)
            {
                IMpClient             mpClient = new MpClient();
                AccessTokenGetRequest request  = new AccessTokenGetRequest()
                {
                    AppIdInfo = new DefAppIdInfo()
                };
                AccessTokenGetResponse response = mpClient.Execute(request);
                if (response.IsError)
                {
                    Logger.WriteTxtLog(string.Format("获取AccessToken发生错误,错误编码为:{0},错误消息为:{1}", response.ErrInfo.ErrCode, response.ErrInfo.ErrMsg));
                    _accessToken = null;
                    return(null);
                }
                _accessToken = response.AccessToken;
                _expTime     = _now.AddSeconds(_accessToken.ExpiresIn - 10);
                Logger.WriteTxtLog(string.Format("获取到AccessToken,值为:{0},有效期:{1}秒", response.AccessToken.AccessToken, response.AccessToken.ExpiresIn));
            }
            return(_accessToken);
        }
Beispiel #7
0
        /// <summary>
        /// 创建AccessToken
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="expire">过期时间(以分钟为单位)</param>
        /// <returns></returns>
        public static AccessTokenInfo CreateAccessToken(List <Claim> claims, int expire = -1)
        {
            var jwt = GetJwtInfo();

            //accesstoken
            if (expire == -1)
            {
                expire = jwt.Expire * 60;
            }
            else
            {
                expire = expire * 60;
            }
            var token = CreateToken(claims, expire);

            //refreshtoken
            claims = new List <Claim>();

            var refreshToken = CreateToken(claims, RefreshTokenExpire);

            AccessTokenInfo tokenInfo = new AccessTokenInfo();

            tokenInfo.ExpiresIn    = expire;
            tokenInfo.AccessToken  = token;
            tokenInfo.RefreshToken = refreshToken;
            return(tokenInfo);
        }
        //accesstoken时限为10分钟,过一阵子进行刷新
        private void RenewAccessToken()
        {
            AccessTokenInfo newAccessToken = RequestTokenAsync().Result;

            //swap the new token with old one
            //Note: the swap is thread unsafe
            this.token = newAccessToken;
        }
Beispiel #9
0
 private void assertAccessTokenResponse(AccessTokenInfo accessTokenInfo)
 {
     Assert.IsNotNull(accessTokenInfo);
     Assert.IsNotNull(accessTokenInfo.Token);
     Assert.AreEqual("Tokenization", accessTokenInfo.TokenizationAccountName);
     Assert.AreEqual("Settlement Reporting", accessTokenInfo.DataAccountName);
     Assert.AreEqual("Dispute Management", accessTokenInfo.DisputeManagementAccountName);
     Assert.AreEqual("Transaction_Processing", accessTokenInfo.TransactionProcessingAccountName);
 }
        public IHttpActionResult Submit([FromBody] AccessTokenInfo itemObj)
        {
            try
            {
                var request = new AuthenticatedRequest();
                if (!request.IsAdminLoggin ||
                    !request.AdminPermissionsImpl.HasSystemPermissions(ConfigManager.AppPermissions.SettingsAdminAccessTokens))
                {
                    return(Unauthorized());
                }

                if (itemObj.Id > 0)
                {
                    var tokenInfo = DataProvider.AccessTokenDao.GetAccessTokenInfo(itemObj.Id);

                    if (tokenInfo.Title != itemObj.Title && DataProvider.AccessTokenDao.IsTitleExists(itemObj.Title))
                    {
                        return(BadRequest("保存失败,已存在相同标题的API密钥!"));
                    }

                    tokenInfo.Title     = itemObj.Title;
                    tokenInfo.AdminName = itemObj.AdminName;
                    tokenInfo.Scopes    = itemObj.Scopes;

                    DataProvider.AccessTokenDao.Update(tokenInfo);

                    request.AddAdminLog("修改API密钥", $"Access Token:{tokenInfo.Title}");
                }
                else
                {
                    if (DataProvider.AccessTokenDao.IsTitleExists(itemObj.Title))
                    {
                        return(BadRequest("保存失败,已存在相同标题的API密钥!"));
                    }

                    var tokenInfo = new AccessTokenInfo
                    {
                        Title     = itemObj.Title,
                        AdminName = itemObj.AdminName,
                        Scopes    = itemObj.Scopes
                    };

                    DataProvider.AccessTokenDao.Insert(tokenInfo);

                    request.AddAdminLog("新增API密钥", $"Access Token:{tokenInfo.Title}");
                }

                return(Ok(new
                {
                    Value = DataProvider.AccessTokenDao.GetAccessTokenInfoList()
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        //Access Token获取授权
        private async Task Authentication()
        {
            token = await RequestTokenAsync();

            accessTokenRenewer = new Timer(new TimerCallback(OnTokenExpiredCallback),
                                           this,
                                           TimeSpan.FromMinutes(RefreshTokenDuration),
                                           TimeSpan.FromMilliseconds(-1));
        }
Beispiel #12
0
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            if (!Page.IsPostBack || !Page.IsValid)
            {
                return;
            }

            if (_id > 0)
            {
                var tokenInfo = DataProvider.AccessTokenDao.GetAccessTokenInfo(_id);

                if (tokenInfo.Title != TbTitle.Text && DataProvider.AccessTokenDao.IsTitleExists(TbTitle.Text))
                {
                    FailMessage("保存失败,已存在相同标题的API密钥!");
                    return;
                }

                tokenInfo.Title = TbTitle.Text;

                tokenInfo.AdminName = DdlAdministrators.SelectedValue;

                var scopes = ControlUtils.GetSelectedListControlValueStringList(CblScopes);
                tokenInfo.Scopes = TranslateUtils.ObjectCollectionToString(scopes);

                DataProvider.AccessTokenDao.Update(tokenInfo);

                AuthRequest.AddAdminLog("修改API密钥", $"Access Token:{tokenInfo.Title}");

                SuccessMessage("API密钥修改成功!");
                //AddWaitAndRedirectScript(PageAdminAccessTokens.PageUrl);
            }
            else
            {
                if (DataProvider.AccessTokenDao.IsTitleExists(TbTitle.Text))
                {
                    FailMessage("保存失败,已存在相同标题的API密钥!");
                    return;
                }

                var scopes = ControlUtils.GetSelectedListControlValueStringList(CblScopes);

                var tokenInfo = new AccessTokenInfo
                {
                    Title     = TbTitle.Text,
                    AdminName = DdlAdministrators.SelectedValue,
                    Scopes    = TranslateUtils.ObjectCollectionToString(scopes)
                };

                DataProvider.AccessTokenDao.Insert(tokenInfo);

                AuthRequest.AddAdminLog("新增API密钥", $"Access Token:{tokenInfo.Title}");

                SuccessMessage("API密钥新增成功!");
                //AddWaitAndRedirectScript(PageAdminAccessTokens.PageUrl);
            }
        }
        public static AccessTokenInfo GetAccessTokenInfo(string token)
        {
            AccessTokenInfo tokenInfo = null;
            var             dict      = AccessTokenManagerCache.GetAccessTokenDictionary();

            if (dict != null && dict.ContainsKey(token))
            {
                tokenInfo = dict[token];
            }
            return(tokenInfo);
        }
        private void RenewAccessToken()
        {
            AccessTokenInfo newAccessToken = HttpPost(AccessUri, this.request);

            //swap the new token with old one
            //Note: the swap is thread unsafe
            this.token = newAccessToken;
            Console.WriteLine(string.Format("Renewed token for user: {0} is: {1}",
                                            this.clientId,
                                            this.token.access_token));
        }
        /// <summary>
        /// Gets the access token from cache or from context token
        /// </summary>
        private void GetAccessToken()
        {
            var contextTokenString = string.Empty;
            var hostWebUrl         = string.Empty;

            if (!IsPostBack)
            {
                contextTokenString = TokenHelper.GetContextTokenFromRequest(Page.Request);
                hostWebUrl         = Page.Request["SPHostUrl"];
                //Session.Add("SPContextToken", contextTokenString);
                ctoken.Value = contextTokenString; //TokenHelper.GetContextTokenFromRequest(Page.Request);
                hweb.Value   = hostWebUrl;
                //Session.Add("SPHostUrl", hostWebUrl);
            }

            contextTokenString = ctoken.Value; //Session["SPContextToken"] == null ? string.Empty : Session["SPContextToken"].ToString();
            if (string.IsNullOrEmpty(contextTokenString))
            {
                //hide everything, then return
#if (DEBUG)
                lblLog.Text = "NULL context token";
#else
                pnlMain.Visible = false;
#endif
                return;
            }
            var hostWeb = new Uri(hweb.Value == null ? string.Empty : hweb.Value.ToString());

            //get the context token details
            SharePointContextToken tokenContent = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

            //now look to see if we have cached an access token for this yet
            if (Session[tokenContent.CacheKey] != null)
            {
                AccessTokenInfo ati = (AccessTokenInfo)Session[tokenContent.CacheKey];

                //check the expiration
                if (DateTime.Now < ati.Expires)
                {
                    accessToken = ati.AccessToken;
                }
            }

            if (string.IsNullOrEmpty(accessToken))
            {
                //get an access token from the refresh token
                accessToken = TokenHelper.GetAccessToken(TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority), hostWeb.Authority).AccessToken;

                //create a new AccessTokenInformation item and set the
                //expiration of the access token to 30 minutes
                //and put it in session state for next time
                Session.Add(tokenContent.CacheKey, new AccessTokenInfo(accessToken, DateTime.Now.AddMinutes(30)));
            }
        }
Beispiel #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        private MemoryCacheEntryOptions GetOptions(AccessTokenInfo token)
        {
            var option = new MemoryCacheEntryOptions()
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(token.ExpiresIn)
            };

            option.RegisterPostEvictionCallback((key, value, reason, state) =>
            {
                TokenEvictioned?.Invoke(key.ToString());
                logger.LogDebug($"缓存已失效。键:{key},值:{value},原因:{reason.ToString()},状态:{state}");
            });
            return(option);
        }
Beispiel #17
0
        /// <summary>
        /// 发起双呼
        /// </summary>
        public async Task <String> StartBack2BackCall(YaeherPhone yaeherPhone)
        {
            AliCCC               aliCCC               = new AliCCC();
            AliAccessToken       aliAccessToken       = new AliAccessToken();
            AliAccessTokenEntity aliAccessTokenEntity = new AliAccessTokenEntity();
            AccessTokenInfo      accessTokenInfo      = new AccessTokenInfo();
            HttpHelper           httpHelper           = new HttpHelper();

            #region 公共参数
            aliCCC.Format         = "JSON";
            aliCCC.Version        = "2017-07-05";
            aliCCC.Timestamp      = DateTime.UtcNow.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
            aliCCC.SignatureType  = "BEARERTOKEN";
            aliCCC.RegionId       = "cn-shanghai";
            aliCCC.SignatureNonce = new RandomCode().GenerateCheckCode(45);
            ///人工维护的token  10个月维护一次
            accessTokenInfo.refresh_token = "s6P4FNojcR0t9Yk6";
            var aliAccessTokens = await aliAccessToken.RefreshAccessToken(accessTokenInfo);

            aliCCC.BearerToken = aliAccessTokens.access_token;
            #endregion

            #region 双呼参数
            aliCCC.Action           = "StartBack2BackCall";
            aliCCC.InstanceId       = "33295c19-1afd-4926-ae46-cd5a28ade3e8";
            aliCCC.CallCenterNumber = yaeherPhone.CallCenterNumber;
            aliCCC.Caller           = yaeherPhone.Caller;
            aliCCC.Callee           = yaeherPhone.Callee;
            #endregion

            string        url           = "https://ccc.cn-shanghai.aliyuncs.com/?";
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(url);
            stringBuilder.Append("&Format=" + aliCCC.Format);
            stringBuilder.Append("&Version=" + aliCCC.Version);
            stringBuilder.Append("&Timestamp=" + aliCCC.Timestamp);
            stringBuilder.Append("&SignatureType=" + aliCCC.SignatureType);
            stringBuilder.Append("&RegionId=" + aliCCC.RegionId);
            stringBuilder.Append("&SignatureNonce=" + aliCCC.SignatureNonce);
            stringBuilder.Append("&BearerToken=" + aliCCC.BearerToken);
            stringBuilder.Append("&Action=" + aliCCC.Action);
            stringBuilder.Append("&InstanceId=" + aliCCC.InstanceId);
            //stringBuilder.Append("&WorkflowId=" + aliCCC.WorkflowId);
            stringBuilder.Append("&CallCenterNumber=" + aliCCC.CallCenterNumber);
            stringBuilder.Append("&Caller=" + aliCCC.Caller);
            stringBuilder.Append("&Callee=" + aliCCC.Callee);
            var AuthorizationCode = await httpHelper.PostResponseAsync(stringBuilder.ToString(), "");

            return(AuthorizationCode.ToString());
        }
Beispiel #18
0
        public void GenerateAccessTokenManualWithPermissions()
        {
            string[] permissions = new string[] { "PMT_POST_Create", "PMT_POST_Detokenize" };

            AccessTokenInfo info =
                GpApiService.GenerateTransactionKey(ENVIRONMENT, APP_ID, APP_KEY, permissions: permissions);

            Assert.IsNotNull(info);
            Assert.IsNotNull(info.Token);
            Assert.AreEqual("Tokenization", info.TokenizationAccountName);
            Assert.IsNull(info.DataAccountName);
            Assert.IsNull(info.DisputeManagementAccountName);
            Assert.IsNull(info.TransactionProcessingAccountName);
        }
Beispiel #19
0
        protected override void ExecuteRequest(HttpContext context)
        {
            (bool isOk, User user) = CheckClaimsForUser(Request, context, _userRepository);
            if (!isOk || user == null)
            {
                return;
            }

            AccessTokenInfo accessTokenInfo = new AccessTokenInfo(user);

            string accessTokenInfoJson = JsonSerializer.Serialize(accessTokenInfo);

            context.Response.StatusCode = StatusCodes.Status200OK;
            context.Response.WriteAsync(accessTokenInfoJson).GetAwaiter().GetResult();
        }
        public void GenerateAccessTokenManual()
        {
            var    environment = Entities.Environment.TEST;
            string appId       = "JF2GQpeCrOivkBGsTRiqkpkdKp67Gxi0";
            string appKey      = "y7vALnUtFulORlTV";

            AccessTokenInfo info = GpApiService.GenerateTransactionKey(environment, appId, appKey);

            Assert.IsNotNull(info);
            Assert.IsNotNull(info.Token);
            Assert.IsNotNull(info.DataAccountName);
            Assert.IsNotNull(info.DisputeManagementAccountName);
            Assert.IsNotNull(info.TokenizationAccountName);
            Assert.IsNotNull(info.TransactionProcessingAccountName);
        }
Beispiel #21
0
        public virtual string CreateToken(string userName, DateTime expirationDate)
        {
            AccessTokenInfo tokenInfo = new AccessTokenInfo();

            tokenInfo.Username    = userName;
            tokenInfo.DateCreated = DateTime.UtcNow;
            tokenInfo.DateExpires = expirationDate;
            tokenInfo.Issuer      = _issuer;

            string token       = tokenInfo.Encrypt();
            var    cacheOption = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(2));

            _cache.Set(userName, token, cacheOption);

            return(token);
        }
        public Authentication(string clientId, string clientSecret)
        {
            this.clientId = clientId;
            this.clientSecret = clientSecret;

            // If clientid or client secret has special characters, encode before sending request
            this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope={2}",
                                          clientId,
                                          clientSecret,
                                          "https://speech.platform.bing.com");

            this.token = HttpPost(AccessUri, this.request);

            // renew the token every specfied minutes
            accessTokenRenewer = new Timer(new TimerCallback(OnTokenExpiredCallback),
                                           this,
                                           TimeSpan.FromMinutes(RefreshTokenDuration),
                                           TimeSpan.FromMilliseconds(-1));
        }
        public string GetAccessToken(AccessTokenRequest request)
        {
            try {
                bool exists = AccessTokenInfo.Exists(request.AuthorizationId);

                // Check for SQLServer-error
                if (!string.IsNullOrEmpty(AccessTokenInfo.ErrorMessage))
                {
                    var msg = AccessTokenInfo.ErrorMessage;
                    AccessTokenInfo.ErrorMessage = "";
                    return(msg);
                }

                if (exists)                                                                                                                                 // = AccessTokenInfo.Exists(request.AuthorizationId)) {
                {
                    var answer = MessageBox.Show("The given AuthorizationCode is already used. Do you want to send anyway to deactivate this integration?", //"Den AuthorizationCode som angivits är redan förbrukad. Vill du skicka ändå för att deaktivera denna integration?",
                                                 "AccessToken existerar",
                                                 MessageBoxButton.YesNo,
                                                 MessageBoxImage.Warning,
                                                 MessageBoxResult.No);

                    if (answer == MessageBoxResult.No)
                    {
                        //return "En AccessToken har redan skapats med given AuthorizationCode.";
                        return("Den AuthorizationCode som angivits är redan förbrukad.");
                    }
                }

                var accessTokenInfo = AccessTokenInfo.GetAccessToken(request.AuthorizationId, request.ClientSecret);

                if (!accessTokenInfo.HasError && !exists)
                {
                    var authorizationCodeEdit = AuthorizationCodeEdit.NewAuthorizationCode();
                    authorizationCodeEdit.AuthorizationCode = request.AuthorizationId;
                    authorizationCodeEdit = authorizationCodeEdit.Save();
                }

                return(accessTokenInfo.AccessToken);
            }
            catch (Exception ex) {
                throw new Exception(ex.Message);
            }
        }
        protected override void ExecuteRequest(HttpContext context)
        {
            (bool isOk, User user) = CheckClaimsForUser(Request, context, _userRepository);
            if (!isOk || user == null)
            {
                return;
            }

            var values = new Dictionary <string, string>
            {
                { "code", Request.GoogleAuthCode },
                { "client_id", "498756810683-agbruikv9b2j9hjs59rrbpb6j13l0l41.apps.googleusercontent.com" },
                { "client_secret", "9QrjOKzI4ldnqXx_uqcrbOK0" },
                { "access_type", "offline" },
                { "redirect_uri", "http://localhost:3000" },
                { "grant_type", "authorization_code" }
            };
            var httpClient = new HttpClient();
            var content    = new FormUrlEncodedContent(values);
            HttpResponseMessage httpResponse = httpClient.PostAsync("https://oauth2.googleapis.com/token", content).GetAwaiter().GetResult();
            var response = httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();

            if (httpResponse.IsSuccessStatusCode)
            {
                JObject tokenAsJson = JObject.Parse(response);
                user.GoogleAccessToken  = tokenAsJson.TryGetString("access_token");
                user.GoogleRefreshToken = tokenAsJson.TryGetString("refresh_token");
                int expires_in = (int)tokenAsJson.TryGetInt("expires_in");
                user.GoogleAccessExpiration = DateTime.Now.AddSeconds(expires_in);

                AccessTokenInfo accessTokenInfo     = new AccessTokenInfo(user);
                string          accessTokenInfoJson = JsonSerializer.Serialize(accessTokenInfo);

                context.Response.WriteAsync(accessTokenInfoJson).GetAwaiter().GetResult();
                _userRepository.Update(user).GetAwaiter().GetResult();
            }
            else
            {
                context.Response.WriteAsync(response).GetAwaiter().GetResult();
            }
        }
        public Authentication(string clientId, string clientSecret)
        {
            this.clientId     = clientId;
            this.clientSecret = clientSecret;

            /*
             * If clientid or client secret has special characters, encode before sending request
             */
            this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope={2}",
                                         HttpUtility.UrlEncode(clientId),
                                         HttpUtility.UrlEncode(clientSecret),
                                         HttpUtility.UrlEncode("https://speech.platform.bing.com"));

            this.token = HttpPost(AccessUri, this.request);

            // renew the token every specfied minutes
            accessTokenRenewer = new Timer(new TimerCallback(OnTokenExpiredCallback),
                                           this,
                                           TimeSpan.FromMinutes(RefreshTokenDuration),
                                           TimeSpan.FromMilliseconds(-1));
        }
        /// <summary>
        /// 将平台返回的HTML转化成MpResponse对象
        /// </summary>
        /// <param name="body">返回的HTML</param>
        /// <returns></returns>
        public AccessTokenGetResponse ParseHtmlToResponse(string body)
        {
            AccessTokenGetResponse response = new AccessTokenGetResponse();

            response.Body = body;

            if (response.HasError())
            {
                response.ErrInfo = response.GetErrInfo();
            }
            else
            {
                AccessTokenInfo token = new AccessTokenInfo()
                {
                    AccessToken = Tools.GetJosnValue(body, "access_token"),
                    ExpiresIn   = Convert.ToInt64(Tools.GetJosnValue(body, "expires_in"))
                };
                response.AccessToken = token;
            }
            return(response);
        }
        private AccessTokenInfo HttpPost(string accessUri, string requestDetails)
        {
            //Prepare OAuth request
            WebRequest webRequest = WebRequest.Create(accessUri);

            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
            webRequest.ContentLength = bytes.Length;
            using (Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            using (WebResponse webResponse = webRequest.GetResponse())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessTokenInfo));
                //Get deserialized object from JSON stream
                AccessTokenInfo token = (AccessTokenInfo)serializer.ReadObject(webResponse.GetResponseStream());
                return(token);
            }
        }
Beispiel #28
0
        public void Update(AccessTokenInfo accessTokenInfo)
        {
            var sqlString = $@"UPDATE {TableName} SET
                {nameof(AccessTokenInfo.Title)} = @{nameof(AccessTokenInfo.Title)}, 
                {nameof(AccessTokenInfo.Scopes)} = @{nameof(AccessTokenInfo.Scopes)},
                {nameof(AccessTokenInfo.RateLimit)} = @{nameof(AccessTokenInfo.RateLimit)},
                {nameof(AccessTokenInfo.UpdatedDate)} = @{nameof(AccessTokenInfo.UpdatedDate)}
            WHERE {nameof(AccessTokenInfo.Id)} = @{nameof(AccessTokenInfo.Id)}";

            IDataParameter[] parameters =
            {
                GetParameter(nameof(accessTokenInfo.Title),       DataType.VarChar,            200, accessTokenInfo.Title),
                GetParameter(nameof(accessTokenInfo.Scopes),      DataType.VarChar,            200, accessTokenInfo.Scopes),
                GetParameter(nameof(accessTokenInfo.RateLimit),   DataType.VarChar,            200, accessTokenInfo.RateLimit),
                GetParameter(nameof(accessTokenInfo.UpdatedDate), DataType.DateTime, DateTime.Now),
                GetParameter(nameof(accessTokenInfo.Id),          DataType.Integer,  accessTokenInfo.Id)
            };

            ExecuteNonQuery(sqlString, parameters);

            AccessTokenManager.ClearCache();
        }
Beispiel #29
0
        public virtual AuthorizationInfo ValidateToken(string token)
        {
            AuthorizationInfo resultAuthorizationInfo = new AuthorizationInfo();

            resultAuthorizationInfo.TokenIsValid = false;

            try
            {
                AccessTokenInfo tokenItem = AccessTokenInfo.Decrypt(token);

                string tokenCached;
                _cache.TryGetValue(tokenItem.Username, out tokenCached);

                if (tokenCached == token)
                {
                    if (tokenItem.Issuer != _issuer)
                    {
                        resultAuthorizationInfo.ErrorMessage = "Not Valid Token";
                        return(resultAuthorizationInfo);
                    }
                }

                else
                {
                    resultAuthorizationInfo.ErrorMessage = "Not Valid Token";
                    return(resultAuthorizationInfo);
                }

                resultAuthorizationInfo.TokenIsValid = true;
                resultAuthorizationInfo.UserName     = tokenItem.Username;
            }
            catch
            {
                return(resultAuthorizationInfo);
            }

            return(resultAuthorizationInfo);
        }
Beispiel #30
0
        public void UploadFile(byte[] content, string filename, string target)
        {
            ocl = DropboxClient.CreateOAuthClient(APP_KEY, APP_SECRET);
            ai  = ocl.GetAuthorizeInfo();

            RequestToken       = ai.RequestToken;
            RequestTokenSecret = ai.RequestTokenSecret;
            redirect_url       = ai.AuthorizeUrl;
            AccessTokenInfo t = ocl.GetAccessToken(RequestToken, RequestTokenSecret);

            Token       = t.Token;
            TokenSecret = t.TokenSecret;

            DropboxClient cl = new DropboxClient(APP_KEY, APP_SECRET, Token, TokenSecret);

            HigLabo.Net.Dropbox.UploadFileCommand ul = new HigLabo.Net.Dropbox.UploadFileCommand();
            ul.Root       = RootFolder.Sandbox;
            ul.FolderPath = target;
            ul.FileName   = filename;
            ul.LoadFileData(content);

            Metadata md = cl.UploadFile(ul);
        }
Beispiel #31
0
        public string GetAccessToken(string appid, string secret)
        {
            //正常情况下access_token有效期为7200秒,这里使用缓存设置短于这个时间即可
            string access_token = MemoryCacheHelper.GetCacheItem <string>("access_token", delegate()
            {
                string grant_type = "client_credential";
                var url           = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}",
                                                  grant_type, appid, secret);

                string result = RequestUtility.HttpGet(url);
                string token  = string.Empty;
                if (result.Contains("access_token"))
                {
                    AccessTokenInfo at = JsonHelper <AccessTokenInfo> .ConvertObjJson(result);
                    token = at.access_token;
                }
                return(token);
            },
                                                                          new TimeSpan(0, 0, 7000)//7000秒过期
                                                                          );

            return(access_token);
        }
 private void RenewAccessToken()
 {
     AccessTokenInfo newAccessToken = HttpPost(AccessUri, this.request);
     //swap the new token with old one
     //Note: the swap is thread unsafe
     this.token = newAccessToken;
 }