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

fix: use correct content type for token request #308

Merged
merged 3 commits into from
Feb 12, 2024
Merged
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
21 changes: 7 additions & 14 deletions config/clients/dotnet/template/Client_OAuth2Client.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,6 @@ public class OAuth2Client {

private static readonly Random _random = new();

private class AuthRequestBody {
[JsonPropertyName("audience")] public string? Audience { get; set; }
[JsonPropertyName("client_id")] public string? ClientId { get; set; }
[JsonPropertyName("client_secret")] public string? ClientSecret { get; set; }
[JsonPropertyName("grant_type")] public string? GrantType { get; set; }
}

/// <summary>
/// Credentials Flow Response
///
Expand Down Expand Up @@ -68,7 +61,7 @@ public class OAuth2Client {

private readonly BaseClient _httpClient;
private AuthToken _authToken = new();
private AuthRequestBody _authRequest { get; set; }
private IDictionary<string, string> _authRequest { get; set; }
private string _apiTokenIssuer { get; set; }

#endregion
Expand All @@ -92,11 +85,11 @@ public class OAuth2Client {

this._httpClient = httpClient;
this._apiTokenIssuer = credentialsConfig.Config.ApiTokenIssuer;
this._authRequest = new AuthRequestBody() {
ClientId = credentialsConfig.Config.ClientId,
ClientSecret = credentialsConfig.Config.ClientSecret,
Audience = credentialsConfig.Config.ApiAudience,
GrantType = "client_credentials"
this._authRequest = new Dictionary<string, string>() {
{ "client_id", credentialsConfig.Config.ClientId },
{ "client_secret", credentialsConfig.Config.ClientSecret },
{ "audience", credentialsConfig.Config.ApiAudience },
{ "grant_type", "client_credentials" }
};
}

Expand All @@ -110,7 +103,7 @@ public class OAuth2Client {
Method = HttpMethod.Post,
BasePath = $"https://{this._apiTokenIssuer}",
PathTemplate = "/oauth/token",
Body = Utils.CreateJsonStringContent(this._authRequest)
Body = Utils.CreateFormEncodedConent(this._authRequest),
};

var accessTokenResponse = await _httpClient.SendRequestAsync<AccessTokenResponse>(
Expand Down
5 changes: 5 additions & 0 deletions config/clients/dotnet/template/Client_Utils.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ public static class Utils {
return new StringContent(json, Encoding.UTF8, "application/json");
}

public static HttpContent CreateFormEncodedConent(IDictionary<string, string> parameters) {
return new FormUrlEncodedContent(parameters.Select(p =>
new KeyValuePair<string, string>(p.Key, p.Value ?? "")));
}

public static string BuildQueryParams(IDictionary<string, string> parameters) {
var query = "";
foreach (var parameter in parameters) {
Expand Down
12 changes: 8 additions & 4 deletions config/clients/dotnet/template/api_test.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,8 @@ namespace {{testPackageName}}.Api {
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"https://{config.Credentials.Config.ApiTokenIssuer}/oauth/token") &&
req.Method == HttpMethod.Post),
req.Method == HttpMethod.Post &&
req.Content.Headers.ContentType.ToString().Equals("application/x-www-form-urlencoded")),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
Expand Down Expand Up @@ -350,7 +351,8 @@ namespace {{testPackageName}}.Api {
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"https://{config.Credentials.Config.ApiTokenIssuer}/oauth/token") &&
req.Method == HttpMethod.Post),
req.Method == HttpMethod.Post &&
req.Content.Headers.ContentType.ToString().Equals("application/x-www-form-urlencoded")),
ItExpr.IsAny<CancellationToken>()
);
mockHandler.Protected().Verify(
Expand Down Expand Up @@ -393,7 +395,8 @@ namespace {{testPackageName}}.Api {
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"https://{config.Credentials.Config.ApiTokenIssuer}/oauth/token") &&
req.Method == HttpMethod.Post),
req.Method == HttpMethod.Post &&
req.Content.Headers.ContentType.ToString().Equals("application/x-www-form-urlencoded")),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
Expand Down Expand Up @@ -447,7 +450,8 @@ namespace {{testPackageName}}.Api {
Times.Exactly(2),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"https://{config.Credentials.Config.ApiTokenIssuer}/oauth/token") &&
req.Method == HttpMethod.Post),
req.Method == HttpMethod.Post &&
req.Content.Headers.ContentType.ToString().Equals("application/x-www-form-urlencoded")),
ItExpr.IsAny<CancellationToken>()
);
mockHandler.Protected().Verify(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ export class Credentials {
client_secret: clientCredentials.clientSecret,
audience: clientCredentials.apiAudience,
grant_type: "client_credentials",
},
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}, {
maxRetry: 3,
Expand Down
10 changes: 6 additions & 4 deletions config/clients/js/template/tests/helpers/nocks.ts.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ export const getNocks = ((nock: typeof Nock) => ({
expiresIn = 300,
statusCode = 200,
) => {
return nock(`https://${apiTokenIssuer}`).post("/oauth/token").reply(statusCode, {
access_token: accessToken,
expires_in: expiresIn,
});
return nock(`https://${apiTokenIssuer}`, { reqheaders: { "Content-Type": "application/x-www-form-urlencoded"} })
.post("/oauth/token")
.reply(statusCode, {
access_token: accessToken,
expires_in: expiresIn,
});
},
listStores: (
basePath = defaultConfiguration.getBasePath(),
Expand Down
6 changes: 3 additions & 3 deletions config/clients/python/template/oauth2.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ class OAuth2Client:
"""
configuration = self._credentials.configuration
token_url = 'https://{}/oauth/token'.format(configuration.api_issuer)
body = {
post_params = {
'client_id': configuration.client_id,
'client_secret': configuration.client_secret,
'audience': configuration.api_audience,
'grant_type': "client_credentials",
}
headers = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'})
raw_response = await client.POST(token_url, headers=headers, body=body);
headers = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'})
raw_response = await client.POST(token_url, headers=headers, post_params=post_params);
if 200 <= raw_response.status <= 299:
try:
api_response = json.loads(raw_response.data)
Expand Down
6 changes: 3 additions & 3 deletions config/clients/python/template/oauth2_sync.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ class OAuth2Client:
"""
configuration = self._credentials.configuration
token_url = 'https://{}/oauth/token'.format(configuration.api_issuer)
body = {
post_params = {
'client_id': configuration.client_id,
'client_secret': configuration.client_secret,
'audience': configuration.api_audience,
'grant_type': "client_credentials",
}
headers = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'})
raw_response = client.POST(token_url, headers=headers, body=body);
headers = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'})
raw_response = client.POST(token_url, headers=headers, post_params=post_params);
if 200 <= raw_response.status <= 299:
try:
api_response = json.loads(raw_response.data)
Expand Down
6 changes: 3 additions & 3 deletions config/clients/python/template/oauth2_test.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ class TestOAuth2Client(IsolatedAsyncioTestCase):
self.assertEqual(auth_header, {'Authorization': 'Bearer AABBCCDD'})
self.assertEqual(client._access_token, 'AABBCCDD')
self.assertGreaterEqual(client._access_expiry_time, current_time + timedelta(seconds=int(120)))
expected_header = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'})
expected_header = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'})
mock_request.assert_called_once_with(
'POST',
'https://www.testme.com/oauth/token',
headers=expected_header,
query_params=None, post_params=None, _preload_content=True, _request_timeout=None,
body={"client_id": "myclientid", "client_secret": "mysecret", "audience": "myaudience", "grant_type": "client_credentials"}
query_params=None, body=None, _preload_content=True, _request_timeout=None,
post_params={"client_id": "myclientid", "client_secret": "mysecret", "audience": "myaudience", "grant_type": "client_credentials"}
)
await rest_client.close()

Expand Down
6 changes: 3 additions & 3 deletions config/clients/python/template/oauth2_test_sync.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,13 @@ class TestOAuth2Client(IsolatedAsyncioTestCase):
self.assertEqual(auth_header, {'Authorization': 'Bearer AABBCCDD'})
self.assertEqual(client._access_token, 'AABBCCDD')
self.assertGreaterEqual(client._access_expiry_time, current_time + timedelta(seconds=int(120)))
expected_header = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'})
expected_header = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'})
mock_request.assert_called_once_with(
'POST',
'https://www.testme.com/oauth/token',
headers=expected_header,
query_params=None, post_params=None, _preload_content=True, _request_timeout=None,
body={"client_id": "myclientid", "client_secret": "mysecret", "audience": "myaudience", "grant_type": "client_credentials"}
query_params=None, body=None, _preload_content=True, _request_timeout=None,
post_params={"client_id": "myclientid", "client_secret": "mysecret", "audience": "myaudience", "grant_type": "client_credentials"}
)
rest_client.close()

Expand Down
Loading