Hi @Jose Daniel Navarro Brito ,
The above works perfectly and the end point ( an ASP.NET CORE Web application) receives the token after the user authenticate via the code below.
I want to send my stored token in the request below
You can try to use Tempdata
to pass your token form your LoginController Login to your PostData method
like:
[HttpPost]
public async Task<ActionResult<string>> Login([FromForm] LoginViewModel model)
{
var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
var body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
using (var posting = await httpClient.PostAsync("Login/login", body))
{
posting.EnsureSuccessStatusCode();
var content = await posting.Content.ReadAsStringAsync();
TempData["token"]= content; // use TempData to pass the token
return Ok(content);
}
return NotFound();
}
Then send the token in the request below using the httpClient.DefaultRequestHeaders.Authorization
:
[HttpPost]
public async Task<ActionResult<string>> PostData([FromForm] DataTableAjaxPostModel model)
{
string token = (string)TempData["token"];
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://localhost:7193/HousingWebAPI/GetData", body);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return Ok(content);
}
return NotFound();
}
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiSm9zZSIsImp0aSI6IjA2NTU1NjZkLWJmOTctNDFiMi1hMzE5LTNmZjEwMDk5YWU2YSIsImV4cCI6MTY5NDk0ODI1MCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDoiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OiJ9.usGppL6QpE7qMeyki1eB503n4nwIJ-xxxWMCMy6dX5o","expiration":"2023-09-17T10:57:30Z"}
Note we need to remove the "token" , because we only need add "Bearer eyjh..."into the hearder not "Bearer ""token":"eyjh.." . So in your _identityService.LoginAsync(model)
you need to return result.token
, not result.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Qing Guo