I am developing a web application which consumes the data from a API
, this at the time of login returns me a token
. This token must be used in the other internal consultations of the application since it must be sent in each request
in header
of post
.
It is here where I do not know how to handle that answer, whether it should be stored in a variable of session["authToken"]
, in a cookie or else transport the token
in some variable const
or static
to be able to use it inside of each user's life cycle.
Since for the first request (solicitud login)
should be sent without the header authorization
but in the others request
once logged, you should add in the line client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(post);
of my class HttpService
the token
for do the other consultations.
It would be great if someone knew a good way to achieve this and that can help me. Below I expand my code. Thanks.
My controller:
public async Task<ActionResult> IndexAsync(Login model)
{
object Token = await PostLoginAsync(model, "api/login");
return View();
}
Method that returns the token
:
public static async Task<Object> PostLoginAsync(Login model, string path)
{
RootObject RootObject = null;
HttpResponseMessage response = await HttpService.GenerateClient().PostAsJsonAsync(path, model);
if (response.IsSuccessStatusCode)
{
RootObject = await response.Content.ReadAsAsync<RootObject>();
}
return RootObject;
}
My class HttpService
:
public static HttpClient GenerateClient()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://0.0.0.0:0000/");
//client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(post);
return client;
}