api icon indicating copy to clipboard operation
api copied to clipboard

Web Auth Required when called via C# HttpClient

Open Jeremy-Code-F opened this issue 2 years ago • 2 comments

Hi, I'm trying to use the Bungie API from a C# httpClient -

// BungieToken.cs

public class BungieToken
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string refresh_token { get; set; }
    public int refresh_expires_in { get; set; }
    public string membership_id { get; set; }
}
[HttpPost("characters")]
    public async Task<IActionResult> GetCharacters([FromBody] BungieToken token)
    {
        if (string.IsNullOrEmpty(token.access_token) || string.IsNullOrEmpty(token.membership_id))
        {
            return BadRequest("Access token or membership ID is missing.");
        }

        var apiKey = _configuration["Bungie:ApiKey"];
        var httpClient = new HttpClient();
        
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token);
        httpClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);

        var response = await httpClient.GetAsync($"https://www.bungie.net/Platform/User/GetMembershipsForCurrentUser");

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            dynamic jsonResponse = JObject.Parse(content);
            return Ok(jsonResponse);
        }
        else
        {
            return BadRequest($"Error fetching character information. {response.Content.ReadAsStringAsync().Result}");
        }
    

I am getting a response back that states

Error fetching character information. {"ErrorCode":99,"ThrottleSeconds":0,"ErrorStatus":"WebAuthRequired","Message":"Please sign-in to continue.","MessageData":{}}

Some logs -

Request headers: Authorization: Bearer MyAccessTokenHere
      X-API-Key: myapikey
      User-Agent: Test Agent/0.0.1
      
info: PortfolioAngular.Controllers.BungieAuthController[0]
      Response headers: Date: Thu, 06 Apr 2023 16:37:26 GMT
      Connection: keep-alive
      Cache-Control: no-cache
      Pragma: no-cache
      Vary: Origin
      X-BungieNext-MID2: 151
      X-BungieNext-Renderer: Frog Blast the Ventcore
      X-UA-Compatible: IE=edge
      X-Ventcore-Status: 99
      Access-Control-Allow-Origin: https://www.bungie.net
      Set-Cookie: bunglefrogblastventcore=; expires=Fri, 06-Apr-2018 16:37:26 GMT; path=/; HttpOnly
      X-SelfUrl: https://www.bungie.net/Platform/User/GetMembershipsForCurrentUser/
      X-Content-Type-Options: nosniff
      X-Frame-Options: SAMEORIGIN
      BNETLB: LB0302
      CF-Cache-Status: DYNAMIC
      Server: cloudflare
      CF-RAY: 7b3b74967e47ad04-ATL

I'm not sure why though, I have an access token, and if I use that access token in postman to call

https://www.bungie.net/Platform/User/GetMembershipsForCurrentUser

Everything works successfully, does anyone see an issue in the provided code that could be causing a problem?

Thanks!

Jeremy-Code-F avatar Apr 06 '23 15:04 Jeremy-Code-F

Simpler console application example that reproduces the issue -

using System.Net.Http.Headers;

var apiKey = "apikey";
var bearerToken ="token";
var url = "https://www.bungie.net/Platform/User/GetMembershipsForCurrentUser";
var httpClient = new HttpClient();
        
HttpRequestMessage message = new (HttpMethod.Get, url);
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
message.Headers.Add("X-API-Key", apiKey);
message.Headers.Add("User-Agent", "TestAgent/7.30.0");

var response = await httpClient.SendAsync(message);

if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}
else
{
    Console.WriteLine($"Error fetching character information. {response.Content.ReadAsStringAsync().Result}");
}

Jeremy-Code-F avatar Apr 06 '23 16:04 Jeremy-Code-F

Hi, @Jeremy-Code-F! Could you try adding trailing '/' at the end of url?

var bearerToken ="token";
var url = "https://www.bungie.net/Platform/User/GetMembershipsForCurrentUser/";
var httpClient = new HttpClient();

This should work

kuleshov-aleksei avatar May 16 '23 15:05 kuleshov-aleksei