I am at my wits end I have been trying for days to get my web app (written in ASP .Net Core 1.1 MVC) to call a web API, using Auth0 as the authentication server.
I have chosen the “Authorization Code Grant Flow” which I believe is the correct one for this scenario?
Now, when a controller action is triggered in my web app, which requires it to call upon the web API, I am trying to get an authorization code, and exchange it for an access token, which I can then use to gain access to the web API. But I seem to not be able to get this to work. Tis is what I have:
public async Task<IActionResult> Index()
{
string accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token")?.Value;
if (accessToken == null || accessToken == "")
return View("Error");
var client = new HttpClient();
var tokenResponse = await client.PostAsync(_auth0Settings.TokenEndpoint,
new FormUrlEncodedContent(new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("client_id", _auth0Settings.ClientId),
new KeyValuePair<string, string>("client_secret", _auth0Settings.ClientSecret),
new KeyValuePair<string, string>("audience", _auth0Settings.ApiIdentifier),
new KeyValuePair<string, string>("code", accessToken)
}));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.StatusCode.ToString());
HttpResponseMessage responseMessage = await client.GetAsync(inspectionsUrl);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
List<Inspection> inspections = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Inspection>>(responseData);
return View(inspections);
}
return View("Error");
}
But at this point I’ve tried so many different things I don’t even know what I have done anymore. The access token I was getting in the first line is really short (fsGscXNbXB-wAXrH) and wasn’t working. Then I realized that is maybe the authorization code which needs to be exchanged for an access code. So then I added the followings lines, but I keep getting a “BAD REQUEST” reply. Any ideas anyone? Unfortunately Auth0 doesn’t have any “Authorization Code Grant Flow” samples. Thanks…