private async Task EnsureLoggedInAsync() { if (_token?.IsValid() == true) { return; } if (_token is null) { _token = LoadToken(); if (_token?.IsValid() == true && _customerName.Equals(_token.CustomerName)) { _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.Token); var testResponse = await _httpClient.GetAsync("api-test"); if (testResponse.IsSuccessStatusCode) { return; } } } await CreateNewTokenAsync(); }
private void StoreToken(TransIpToken token) { var fullPath = Environment.ExpandEnvironmentVariables(@"%HOME%\.acme\transip_token.json"); var directoryPath = Path.GetDirectoryName(fullPath); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var json = JsonConvert.SerializeObject(token, Formatting.Indented); File.WriteAllText(fullPath, json); }
private async Task CreateNewTokenAsync() { var nonce = new byte[16]; RandomNumberGenerator.Fill(nonce); var request = new TokenRequest { Login = _customerName, Nonce = Convert.ToBase64String(nonce) }; (string signature, string body) = await SignRequestAsync(request); var response = await new HttpClient().SendAsync( new HttpRequestMessage(HttpMethod.Post, new Uri(_httpClient.BaseAddress, "auth")) { Headers = { { "Signature", signature } }, Content = new StringContent(body, Encoding.UTF8, "application/json") }); response.EnsureSuccessStatusCode(); var tokenResponse = await response.Content.ReadAsAsync <TokenResponse>(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.Token); _token = new TransIpToken { CustomerName = _customerName, Token = tokenResponse.Token, Expires = DateTimeOffset.FromUnixTimeSeconds(tokenResponse.GetTokenExpiration()) }; StoreToken(_token); }