Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Token in GET parameters in case Headers authentication is down #145

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ protected virtual void AssertRequest(CallInfo callInfo, IEndpointClient client,
uri = builder.Uri;
}

Assert.Equal(uri.AbsoluteUri, callInfo.ArgAt<IWebApiRequest>(0).Options.Url.AbsoluteUri);
Assert.Equal(uri.AbsoluteUri, callInfo.ArgAt<IWebApiRequest>(0).Options.UrlWithoutAuth.AbsoluteUri);
var requestHeaders = callInfo.ArgAt<IWebApiRequest>(0).Options.RequestHeaders;
Assert.Contains(new KeyValuePair<string, string>("Accept", "application/json"), requestHeaders);
Assert.Contains(new KeyValuePair<string, string>("User-Agent", ((Gw2WebApiBaseClient)client).Connection.UserAgent), requestHeaders);
Expand Down
21 changes: 20 additions & 1 deletion Gw2Sharp/WebApi/Http/HttpClient.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Gw2Sharp.Extensions;
Expand Down Expand Up @@ -67,7 +68,7 @@ public Task<IHttpResponseStream> RequestStreamAsync(IWebApiRequest request, Canc

async Task<IHttpResponseStream> ExecAsync()
{
using var message = new HttpRequestMessage(HttpMethod.Get, request.Options.Url);
using var message = new HttpRequestMessage(HttpMethod.Get, request.Options.UrlWithoutAuth);
message.Headers.AddRange(request.Options.RequestHeaders);

Task<HttpResponseMessage>? task = null;
Expand All @@ -84,6 +85,24 @@ async Task<IHttpResponseStream> ExecAsync()
task = httpClient.SendAsync(message, cancellationToken);
var responseMessage = await task.ConfigureAwait(false);

if (responseMessage.StatusCode == HttpStatusCode.NotFound &&
message.Headers.Contains("Authorization") &&
message.Headers.GetValues("Authorization").First() != "Bearer")
{
using var newMessage = new HttpRequestMessage(HttpMethod.Get, request.Options.Url);
foreach (var header in message.Headers)
{
if (header.Key == "Authorization")
continue;

newMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);
}


task = httpClient.SendAsync(newMessage, cancellationToken);
responseMessage = await task.ConfigureAwait(false);
}

await responseMessage.Content.LoadIntoBufferAsync().ConfigureAwait(false);
#if NET5_0_OR_GREATER
var stream = await responseMessage.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
Expand Down
16 changes: 16 additions & 0 deletions Gw2Sharp/WebApi/Http/WebApiRequestOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,22 @@ public Uri Url
}
}

/// <summary>
/// The URL without the authentication parameter.
/// </summary>
public Uri UrlWithoutAuth
{
get
{
var builder = new UriBuilder(this.BaseUrl);
builder.Path += this.EndpointPath;
if (!string.IsNullOrEmpty(this.PathSuffix))
builder.Path += !this.PathSuffix.StartsWith("/", StringComparison.InvariantCulture) ? "/" : string.Empty + this.PathSuffix;
builder.Query = string.Join("&", this.EndpointQuery.Where(x => x.Key != "access_token").Select(x => $"{Uri.EscapeDataString(x.Key)}{(x.Value != null ? $"={Uri.EscapeDataString(x.Value)}" : "")}"));
return builder.Uri;
}
}

#pragma warning disable CA2227 // Collection properties should be read only
/// <summary>
/// The request headers to use in the web request.
Expand Down
12 changes: 8 additions & 4 deletions Gw2Sharp/WebApi/V2/RequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ internal class RequestBuilder
private readonly IConnection connection;
private readonly IGw2Client gw2Client;
private readonly string? authorization;
private readonly string? token;
private readonly string? locale;
private readonly string userAgent;

Expand All @@ -59,7 +60,8 @@ public RequestBuilder(IEndpointClient endpointClient, IConnection connection, IG
this.connection = connection;
this.gw2Client = gw2Client;

this.authorization = endpointClient.IsAuthenticated ? $"{BEARER} {connection.AccessToken}" : null;
this.token = endpointClient.IsAuthenticated ? connection.AccessToken : null;
this.authorization = endpointClient.IsAuthenticated ? $"{BEARER} {this.token}" : null;
this.locale = endpointClient.IsLocalized ? connection.LocaleString : null;
this.userAgent = connection.UserAgent;
}
Expand Down Expand Up @@ -133,12 +135,14 @@ public IWebApiRequest Page(int page, int pageSize = MAX_PAGE_SIZE)

private IDictionary<string, string>? BuildQueryParams(IDictionary<string, string>? additionalQueryParams = null)
{
if (this.queryParams.Count == 0)
return additionalQueryParams;
var combinedQueryParams = new Dictionary<string, string>(this.queryParams);

if (!string.IsNullOrWhiteSpace(this.token))
combinedQueryParams["access_token"] = this.token;

if (additionalQueryParams != null)
combinedQueryParams.AddRange(additionalQueryParams);
return combinedQueryParams;
return (combinedQueryParams.Count == 0) ? additionalQueryParams : combinedQueryParams;
}

private IDictionary<string, string> BuildHeaders()
Expand Down