'HTTP-Authentication add token to Client
I could manage to get the API-Server sending me a Token. Also i can store the Token in a CustomModel. But How can i attach the Token to my HttpClient which i want to use.
Here's my Login and function:
public static async Task<AuthToken> Login()
{
var userName = "administrator";
var passwd = "********";
var ClientID = "acef4bf9988848a0bff79485d1ac2648";
var ClientScrt = "********************";
var url = "https://****.********.****/MobiControl/api/token";
string body = $"grant_type=password&username={userName}&password={passwd}"; //"grant_type=password&username=Administrator&password=1";
var payload = new StringContent(body, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
var authHeader = Encoding.ASCII.GetBytes($"{ClientID}:{ClientScrt}");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authHeader));
var result = client.PostAsync(url, payload);
var token = await result.Result.Content.ReadAsStringAsync();
AuthToken authToken = JsonConvert.DeserializeObject<AuthToken>(token);
Console.WriteLine(token);
ApiHelper.InitializeClient();
return authToken;
}
}
and here's my Client constructor:
the commented line makes the problem(s), it gives me two faults: "An object reference is required for the nonstatic field, method, or property 'member'"
public static class ApiHelper
{
public static HttpClient ApiClient { get; set; }
public static void InitializeClient()
{
ApiClient = new HttpClient();
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//ApiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AuthToken.Token_type, AuthToken.Access_token);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
