public async Task TestValid() { var client = new Client(); GetTokenResponse response = await client.GetToken(); Assert.IsTrue(response.token.Length > 10); }
/// <summary> /// Retrieve a token from the database /// </summary> /// <param name="token">The token to retrive</param> /// <returns>A <see cref="Task<&g;"/> object for task synchronization and retrieving the token information</returns> public async Task <GetTokenResponse> GetToken(string token) { using var connection = new SqlConnection(_connectionSTring); var getTokenResponse = new Dictionary <int, GetTokenResponse>(); await connection.OpenAsync(); var result = await connection.QueryAsync <TokenData, UserData, GetTokenResponse>("EXEC dbo.Token_Get_ByToken @Token = @Token", (t, u) => { if (!getTokenResponse.TryGetValue(t.Id, out GetTokenResponse response)) { response = new GetTokenResponse() { Id = t.Id, OwnerId = t.Owner, Expires = t.Expires, Token = t.Token }; } if (u != null) { response.UserName = u.UserName; response.Email = u.Email; } return(response); }, new { Token = token }, splitOn : "Id"); return(result.FirstOrDefault()); }
private GetTokenResponse DoGetToken(CardTokenBsa card_token) { GetTokenResponse response = null; Dictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("apikey", this.publicApiKey); this.restClientGetTokenBSA = new RestClient(this.endpoint, headers, CONTENT_TYPE_APP_JSON); string cardTokenJson = CardTokenBsa.toJson(card_token); RestResponse result = this.restClientGetTokenBSA.Post("tokens", cardTokenJson); if (!String.IsNullOrEmpty(result.Response)) { response = JsonConvert.DeserializeObject <GetTokenResponse>(result.Response); } if (result.StatusCode != STATUS_CREATED) { if (isErrorResponse(result.StatusCode)) { throw new GetTokenResponseException(result.StatusCode.ToString(), JsonConvert.DeserializeObject <ErrorResponse>(result.Response)); } else { throw new GetTokenResponseException(result.StatusCode + " - " + result.Response, response); } } return(response); }
public static GetTokenResponse CreateFromResponse(string response) { GetTokenResponse token = new GetTokenResponse(response); File.WriteAllText(CacheFile, response); return(token); }
private static async Task <string> RefreshAuthTokenAsync(GetTokenResponse oldToken) { Uri uri = new Uri(GetTokenUrl); HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.Method = "POST"; byte[] authData = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Constants.OAuth.ClientID, Constants.OAuth.ClientSecret)); req.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", Convert.ToBase64String(authData)); req.ContentType = "application/x-www-form-urlencoded"; using (StreamWriter writer = new StreamWriter(await req.GetRequestStreamAsync())) { string requestBody = string.Format("grant_type=refresh_token&redirect_uri=oob&refresh_token={0}", oldToken.RefreshToken); await writer.WriteAsync(requestBody); await writer.FlushAsync(); } string response = string.Empty; using (HttpWebResponse res = await req.GetResponseAsync() as HttpWebResponse) using (StreamReader responseBody = new StreamReader(res.GetResponseStream())) { response = await responseBody.ReadToEndAsync(); } return(response); }
public static GetTokenResponse CreateFromResponse(string response) { GetTokenResponse token = new GetTokenResponse(response); CachedToken cachedToken = new CachedToken(response, token.expires); File.WriteAllText(CacheFile, JsonConvert.SerializeObject(cachedToken)); return(token); }
public ActionResult GetTokenBSA(CardTokenBsaDTO cardTokenBsaDTO) { DecidirConnector decidir = new DecidirConnector(cardTokenBsaDTO.AmbienteId, cardTokenBsaDTO.privateApiKey, cardTokenBsaDTO.publicApiKey); GetTokenResponse respuesta = decidir.GetToken(cardTokenBsaDTO.cardTokenBsa); return(Json(respuesta)); }
public async Task TestValidOptions() { var client = new Client(); GetTokenOptions opts = new GetTokenOptions("user", 1000, false); GetTokenResponse response = await client.GetToken(opts); Assert.IsTrue(response.token.Length > 10); }
public GetTokenResponse GetToken(GetTokenRequest request) { GetTokenResponse response = new GetTokenResponse(); response.IsTrue = false; response.Status = 0; if (request != null) { try { if (string.IsNullOrEmpty(request.AppId) || string.IsNullOrEmpty(request.Secret) || string.IsNullOrEmpty(request.Session_Id)) { response.Status = 0; response.Msg = "请求参数有误,请检查!"; } else { //获取三方APP信息 AppSettingInfo app = SystemFactory.Instance.GetSystemAppConfig(request.AppId, request.Secret); if (app != null) { if (app.AppStatus == AppStatus.Reviewed) { //更新Token,同时更新过期时间) string newToken = SystemFactory.Instance.UpdateTokenInfo(app); response.IsTrue = true; response.Access_Token = newToken; response.Status = 1; response.Msg = "请求成功!"; response.Expires_In = 7200; response.CorpCode = app.CorpCode; response.SubCorpCode = app.SubCorpCode; response.CorpName = app.CorpName; } else { response.Msg = "请联系管理员审批系统!"; } } else { response.Msg = "该APP未在码中心注册,或密钥有误!请重试或联系管理员"; } } } catch (Exception exception) { response.Msg = exception.Message; } } else { response.Msg = "非法请求,请重试!"; } return(response); }
public async Task AuthorizeRequestAsync(HttpWebRequest req) { if (this.getTokenResponse.IsExpired) { this.getTokenResponse = GetTokenResponse.CreateFromResponse(await RefreshAuthTokenAsync(this.getTokenResponse)); } req.Headers[HttpRequestHeader.Authorization] = "Bearer " + this.getTokenResponse.AccessToken; }
public ActionResult <string> Get(string deviceId) { var token = JwtUtil.GenerateToken(deviceId); var response = new GetTokenResponse() { Result = (int)ResultCode.Success, Token = token, GameServerAddress = _config.GameServerAddress }; return(JsonConvert.SerializeObject(response)); }
public async Task <bool> InitializeAuthorizationAsync(string authorizationCode) { if (this.getTokenResponse != null) { return(true); } this.getTokenResponse = GetTokenResponse.CreateFromResponse(await GetNewAuthTokenAsync(authorizationCode)); return(this.getTokenResponse != null); }
public void DoFlow() { //1 取得Token Token //2 商品變價 api/Product/ChangeProductPrice //3 商品查詢(檢查) api/Product/ProductQuery getUserByUserInfo = new GetUserByUserInfo() { password = password, userName = userName }; getTokenResponse = GetToken(); GetChangeProductPrice(); GetProductQuery(); }
public async Task InitPortalUser() { token = await Api.GetToken("*****@*****.**", "Password1234"); SettingsService.Instance.Token = token.access_token; SettingsService.Instance.TokenExpiration = DateTime.Now.AddSeconds(token.expires_in); var infoResult = await ApiService.Instance.GetMyInfo(); var infoData = infoResult.Data; SettingsService.Instance.AxCustomerId = infoData.CustomerInfo.Key; SettingsService.Instance.MyInfo = infoData; }
public void DoFlow() { //1 取得Token Token //2 變更出貨狀態 api/ShipManage/ChangeShipStatus //3 查詢出貨狀態(檢查) api/ShipManage/Search getUserByUserInfo = new GetUserByUserInfo() { password = password, userName = userName }; getTokenResponse = GetToken(); GetChangeShipStatus(); GetSearch(); }
public void DoFlow() { //1 取得Token Token //2 變更商品銷售狀態 api/Product/ChangeSaleStatus //3 商品查詢(檢查) api/Product/ProductQuery getUserByUserInfo = new GetUserByUserInfo() { password = password, userName = userName }; getTokenResponse = GetToken(); GetChangeSaleStatus(); GetProductQuery(); }
public void DoFlow() { //1 取得Token Token //2 商品變量 api/Product/AccessedNum //3 商品查詢(檢查) api/Product/ProductQuery getUserByUserInfo = new GetUserByUserInfo() { password = password, userName = userName }; getTokenResponse = GetToken(); GetAccessedNum(); GetProductQuery(); }
private async Task UnitDriverUser() { token = await Api.GetToken("*****@*****.**", "bassam", false); SettingsService.Instance.Token = token.access_token; SettingsService.Instance.TokenExpiration = DateTime.Now.AddSeconds(token.expires_in); var infoResult = await ApiService.Instance.GetMyInfo(); var infoData = infoResult.Data; SettingsService.Instance.AxCustomerId = infoData.CustomerInfo.Key; SettingsService.Instance.MyInfo = infoData; }
public async Task <IActionResult> GetToken([FromBody] GetTokenRequest applicationUser) { var security = _securityRepository.GetSecurity(); if (security.ApiAccessDisabled) { _logger.LogWarning( "Api access is denied becasuse to many failed get token attempts. To enable access open manually Security.json file and set property ApiAccessDisabled to false. "); throw new HttpError(HttpStatusCode.Forbidden); } var identityTask = GetClaimsIdentity(applicationUser, security); var identity = await identityTask; if (identity == null) { _logger.LogInformation( $"Invalid username ({applicationUser.Username}) or password ({applicationUser.Password})"); _securityRepository.IncreaseFailedGetTokenAttempts(security); return(BadRequest("Invalid credentials")); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, applicationUser.Username), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response2 = new GetTokenResponse { Token = encodedJwt, ExpiresIn = (int)_jwtOptions.ValidFor.TotalSeconds }; return(Ok(response2)); }
public void DoFlow() { //1 取得Token Token //2 查詢規格表 api/Product/ProductSpecCacheLookup //3 填寫規格表內容 api/Product/InsertProductFormSpec //4 商品查詢(檢查) api/Product/ProductQuery getUserByUserInfo = new GetUserByUserInfo() { password = password, userName = userName }; getTokenResponse = GetToken(); GetProductSpecCacheLookup(); GetInsertProductFormSpec(); GetProductQuery(); }
public static GetTokenResponse Unmarshall(UnmarshallerContext _ctx) { GetTokenResponse getTokenResponse = new GetTokenResponse(); getTokenResponse.HttpResponse = _ctx.HttpResponse; getTokenResponse.RequestId = _ctx.StringValue("GetToken.RequestId"); GetTokenResponse.GetToken_Token token = new GetTokenResponse.GetToken_Token(); token.Domain = _ctx.StringValue("GetToken.Token.Domain"); token.LicenseKey = _ctx.StringValue("GetToken.Token.LicenseKey"); token.Pid = _ctx.StringValue("GetToken.Token.Pid"); token.InternalDomain = _ctx.StringValue("GetToken.Token.InternalDomain"); getTokenResponse.Token = token; return(getTokenResponse); }
// チャットに参加 public async ValueTask JoinToChatAsync() { var res = await _http.GetStringAsync("/api/GetToken"); _getTokenResponse = JsonSerializer.Deserialize <GetTokenResponse>(res, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }); _chatClient = new ChatClient( new Uri(_communicationServiceSettings.Endpoint), new CommunicationUserCredential(_getTokenResponse.Token)); _chatThreadClient = _chatClient.GetChatThreadClient(_getTokenResponse.ThreadId); }
public void DoFlow() { //1 取得Token Token //2 查詢規格表 api/Product/ProductSpecCacheLookup //3 修改 V2 api/Product/SaleSKU/v2 //4 商品查詢(檢查) api/Product/ProductQuery getUserByUserInfo = new GetUserByUserInfo() { password = password, userName = userName }; getTokenResponse = GetToken(); GetProductSpecCacheLookup(); GetProductV2(); GetProductQuery(); }
protected async Task <TokenValidationResult> ValidateToken(GetTokenResponse getTokenResponse) { if (getTokenResponse == null) { return(TokenValidationResult.NoToken); } if (getTokenResponse.Expires < DateTime.UtcNow) { await _userRepository.DeleteToken(getTokenResponse.Token); return(TokenValidationResult.TokenExpired); } return(TokenValidationResult.Ok); }
public void DoFlow() { //1 取得Token Token //2 查詢前台分類 api/Product/FrontendProductCategoryOfFormIDsQuery //3 查詢規格表 api/Product/ProductSpecCacheLookup //4 新增 V2 api/Product/SaleSKU/v2 //5 商品查詢(檢查) api/Product/ProductQuery getUserByUserInfo = new GetUserByUserInfo() { password = password, userName = userName }; getTokenResponse = GetToken(); GetFrontendProductCategoryOfFormIDsQuery(); GetProductSpecCacheLookup(); GetProductV2(); GetProductQuery(); }
public async Task <GetTokenResponse> GetTokenAsync() { if (AccessToken == null || int.Parse(AccessToken?.expires_in) < 100) { var request = new HttpRequestMessage(HttpMethod.Post, $"{_settings.TenantId}/oauth2/token") { Content = new StringContent($"resource={_settings.Resource}&client_id={_settings.Client_id}&client_secret={_settings.Client_secret}&grant_type={_settings.Grant_type}", Encoding.UTF8, "application/x-www-form-urlencoded") }; using (var response = await _client.SendAsync(request)) { var stream = await response.Content.ReadAsStreamAsync(); response.EnsureSuccessStatusCode(); AccessToken = stream.ReadAndDeserializeFromJson <GetTokenResponse>(); } } return(AccessToken); }
/// <summary> /// Produce a new token using the apikeyserver /// </summary> /// <returns> string token </returns> public string getToken() { //Should combaine apikeyserver with cosnt path string Uri resolvedUri = new Uri(apiKeyServer, string.Format(path, tenantId)); var formParams = new[] { new KeyValuePair <string, string>("grant_type", "refresh_token"), new KeyValuePair <string, string>("client_id", "reportium"), new KeyValuePair <string, string>("refresh_token", apiKey) }; var form = new FormUrlEncodedContent(formParams); //By defualt supporting UTF-8 var response = httpClient.PostAsync(resolvedUri, form).Result.Content.ReadAsStringAsync().Result; GetTokenResponse getTokenResponse = JsonConvert.DeserializeObject <GetTokenResponse>(response.ToString()); return(getTokenResponse.getAccess_token()); }
public IDictionary <string, object> GetToken() { try { var tokenRequest = new GetTokenRequest(Int64.Parse(this.CnpjParceiro), Int32.Parse(this.CodigoParceiro), "1.0"); if (_token == null) { _token = this.Cliente.GetTokenAsync(tokenRequest).Result; } else { if (!ValidarToken()) { _token = this.Cliente.GetTokenAsync(tokenRequest).Result; } } if ((_token.erro?.Length ?? 0) > 0) { return(new Dictionary <string, object>() { { "error", _token.erro } }); } return(null); } catch (Exception ex) { var error = new erro() { codigo = "SAL-0001", descricao = "Não foi possível recuperar o token, serviço indiponível!", detalhe = ex.Message }; return(new Dictionary <string, object>() { { "error", error } }); } }
public static GetTokenResponse CreateFromCache() { if (File.Exists(CacheFile)) { string response = File.ReadAllText(CacheFile); try { GetTokenResponse token = new GetTokenResponse(response); if (!token.IsExpired) { return(token); } } catch { } File.Delete(CacheFile); } return(null); }
public async Task <MessageModel <Logins> > Login([FromForm] string username, [FromForm] string password) { if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { return new MessageModel <Logins>() { Msg = "账号和密码不能为空=" + username + '=' + password } } ; var logins = await _context.Logins.FirstOrDefaultAsync(l => l.LoginName == username && l.LoginPassword == password); if (logins == null) { return new MessageModel <Logins>() { Msg = "账户和密码错误" } } ; if (logins.Status == Enums.UserStatus.Normal) { //获取token var token = await GetTokenResponse.GetTokenClient(); await _redis.SetString("LoginId", logins.Id.ToString(), TimeSpan.FromMinutes(30)); return(new MessageModel <Logins>() { Msg = token, Response = logins, Success = true }); } return(new MessageModel <Logins>() { Msg = "账号和密码不能为空" }); }