AWS Sig v4 Signing for API Gateway - aws-sdk

Is there some way to lookup the region of an apigateway endpoint and use that to sign your requests with sigv4?
I'm using the aws sdk to do the signing like so
let req = new AWS.HttpRequest( endpoint );
req.method = 'POST';
req.path = endpoint.path;
req.region = QueryApi.getBaseUrlRegion( this._baseUrl );
req.body = JSON.stringify( body );
req.headers[ 'Host' ] = endpoint.host
req.headers[ 'presigned-expires' ] = false
req.headers[ 'Content-Type' ] = 'application/json'
let signer = new AWS.Signers.V4( req, 'execute-api' )
signer.addAuthorization( this._awsCreds, new Date() )
Right now I am parsing the region from the internal aws execute-api url, but this won't work with a custom dns name.
Are the only options using a config, or doing a DNS lookup?

Unfortunately, currently there isn't a way to look up the region when using a custom domain name. Using DNS lookup will not work as well because API Gateway is fronted by CloudFront distributions.

Related

How to send POST request using Julia lang HTTP library to a Django RESTFUL API (DRF)

There is very limited documentation when it comes to the HTTP library in Julia Lang. Not just that, but there are no up to date Stack Overflow questions regarding the HTTP library in general.
With that said, how do you send POST requests using Julia + HTTP to a Django Restful API (DRF)?
Julia 1.7, 1.8
If you are sending json formatted data (simple Django POST request):
begin
using JSON
using HTTP
const url = "http://127.0.0.1:8000/api/profile"
payload = Dict("email" => "email#email.com", "password" => "12345password")
response = HTTP.request(
"POST", url, ["Content-Type" => "application/json"], JSON.json(payload))
# this is necessary, JULIA discontinued python style Dictionaries
response = JSON.parse(String(response.body))
println(response)
end
If you are sending header information like Authentication tokens, etc.
begin
using JSON
using HTTP
const url = "http://127.0.0.1:8000/api/profile"
payload = Dict("email" => "email#email.com", "password" => "12345password")
access_token = "some access token"
headers = Dict(
"Content-Type" => "application/json",
"Authorization" => "Bearer $access_token")
response = HTTP.request(
"POST", url, headers, JSON.json(payload))
# this is necessary, JULIA discontinued python style Dictionaries
response = JSON.parse(String(response.body))
println(response)
end

M Language - How to get JSON in HTTP Request Body? (Vimeo API Unsupported Grant Type Error)

I am attempting to create my first PowerBI Custom Connecter to connect to the Vimeo API. I am stuck on the final step of the authorization flow - getting back an access token. When trying out the Connecter in PowerBI, it seems to authenticate properly when I hit the access token endpoint, but I get back a warning "[unsupported_grant_type] Unsupported grant type"
It appears I am not sending the grant_type properly in the request. Here are Vimeo's requirements of what is sent along in the header and body of the request:
Header
Set value to
Authorization
basic base64_encode(x:y), where x is the client identifier and y is the client secret
Content-Type
application/json
Accept
application/vnd.vimeo.*+json;version=3.4
"In the request body, send the grant_type field with the value authorization_code. You must also set code to the authorization code string that you just received and redirect_uri to the redirect URI that you specified previously — don't use a different redirect URI."
{
"grant_type": "authorization_code",
"code": "{code}",
"redirect_uri": "{redirect_uri}"
}
Here is a snippet of code from the Customer Connector I am building. It is within this TokenMethod function that I am trying to fulfill the requirements of the table above. I am getting the sense I am not correctly placing the JSON in the body of the request, but I am stuck on what to try next:
TokenMethod = (grantType, tokenField, code) =>
let
queryString = [
grant_type = "authorization_code",
redirect_uri = redirect_uri,
client_id = client_id,
client_secret = client_secret
],
queryWithCode = Record.AddField(queryString, tokenField, code),
authKey = "Basic " & Binary.ToText(Text.ToBinary("client_id:client_secret"),BinaryEncoding.Base64),
tokenResponse = Web.Contents(token_uri, [
Content = Text.ToBinary(Uri.BuildQueryString(queryWithCode)),
Headers = [
#"Authorization" = authKey,
#"Content-type" = "application/json",
#"Accept" = "application/vnd.vimeo.*+json;version=3.4"
],
ManualStatusHandling = {400}
]),
body = Json.Document(tokenResponse),
result = if (Record.HasFields(body, {"error", "error_description"})) then
error Error.Record(body[error], body[error_description], body)
else
body
in
result;
I'm wondering if someone could please point out where I might be going astray in the code and why I am receiving the [unsupported_grant_type] error.
Many thanks for your time!
I changed Content-Type to "application/x-www-form-urlencoded" and it worked!

LoginRadius Validating access token .net core

I am trying to validate my access token (not JWT) with LoginRadius, I can do the login but after when I call my API I always get unauthorized or different errors according to my Authentication configuration, I am using like this. I believe the authority url is not correct but I couldn't find any other
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("login-radius", options => {
// Set the authority to your Auth0 domain
options.Authority = $"https://api.loginradius.com/identity/v2/auth/";
// Configure the Auth0 Client ID and Client Secret
options.ClientId = Configuration["ClientId"];
options.ClientSecret = Configuration["ClientSecret"];
// Set response type to code
options.ResponseType = OpenIdConnectResponseType.Code;
options.Scope.Clear();
options.Scope.Add("openid");
options.CallbackPath = new PathString("/callback");
options.ClaimsIssuer = "loginradius";
// Saves tokens to the AuthenticationProperties
options.SaveTokens = true;
});
I believe you are trying to setup OIDC, and to configure it, please refer to the LoginRadius docs on OIDC, as it needs few things that need to be configured in the Admin Console and the correct authority URL: https://www.loginradius.com/docs/single-sign-on/tutorial/federated-sso/openid-connect/openid-connect-overview/#otheropenidfunctionality6
Please refer to the OIDC discovery endpoint, which provides a client with configuration details about the OpenID Connect metadata of the Loginradius App.
URL Format: https://cloud-api.loginradius.com/sso/oidc/v2/{sitename}/{oidcappname}/.well-known/openid-configuration
My account didn't have access to few features

How to pull data from Toggl API with Power Query?

First timer when it comes to connecting to API. I'm trying to pull data from Toggl using my API token but I can't get credentials working. I tried to replicate the method by Chris Webb (https://blog.crossjoin.co.uk/2014/03/26/working-with-web-services-in-power-query/) but I can't get it working. Here's my M code:
let
Source = Web.Contents(
"https://toggl.com/reports/api/v2/details?workspace_id=xxxxx&client=xxxxxx6&billable=yes&user_agent=xxxxxxx",
[
Query=[ #"filter"="", #"orderBy"=""],
ApiKeyName="api-token"
])
in
Source
After that I'm inputting my API Token into Web API method in Access Web content windows but I get an error that credentials could not be authenticated. Here's Toggl API specification:
https://github.com/toggl/toggl_api_docs/blob/master/reports.md
Web.Contents function receives two parameters: url + options
Inside options, you define the headers and the api_key, and other queryable properties, such as:
let
baseUrl = "https://toggl.com/",
// the token part can vary depending on the requisites of the API
accessToken = "Bearer" & "insert api token here"
options = [
Headers = [Authorization = accessToken, #"Content-Type" =
"application/Json"], RelativePath ="reports/api/v2/details", Query =
[workspace_id=xxxxx, client=xxxxxx6 , billable=yes, user_agent=xxxxxxx]
]
Source = Web.Contents(baseUrl, options)
// since Web.Contents() doesn't parse the binaries it fetches, you must use another
// function to see if the data was retreived, based on the datatype of the data
parsedData = Json.Document(Source)
in
parsedData
The baseUrl is the smallest url that works and never changes;
The RelativePath is the next part of the url before the first "?".
The Query record is where you define all the attributes to query as a record.
This is usually the format, but check the documentation of the API you're querying to see if it is similar.

Python auth for kms

I'm new to google cloud kms product, is there a tutorial on how to authenticate ( from third party server ) kms with python? The goal is to access the public key, encrypt the data ( async ). Another server will have more permissions and will be able to decrypt. I don't want to use gcloud shell client.
I solved it using the json file. I will post the code if it help someone in the future.
def encrypt_rsa(plaintext, key_name):
# get the public key
credentials = service_account.Credentials.from_service_account_file(
'the_key_file_of_service_account.json')
scoped_credentials = credentials.with_scopes(
['https://www.googleapis.com/auth/cloud-platform'])
client = kms_v1.KeyManagementServiceClient(credentials=credentials)
response = client.get_public_key(key_name)
key_txt = response.pem.encode('ascii')
public_key = serialization.load_pem_public_key(key_txt, default_backend())
# encrypt plaintext
pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None)
plaintext = base64.urlsafe_b64encode(plaintext.encode("ascii"))
return public_key.encrypt(plaintext, pad)