Amazon Cognito: invalid_client when refreshing token - javascript

I'm trying to get a new accessToken and idToken by hitting the endpoint oauth2/token.
I got the refresh token from cognitoUser.authenticateUser() method in amazon-cognito-identity-js
Here's my sample request in postman:
URL (seems fine)
BODY (seems fine)
HEADERS (not sure)
Authorization: Basic Base64(client_id) - i used btoa() function in JS
Note: The pool does not have a client secret
Problem: When I test this out, this is the response
I believe I supplied the right data as documented here:
https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html
grant_type: refresh_tokenclient_id: required if does not have a secretrefresh_token: refresh token here
Is there something that I'm missing or something I did wrong? I am not very familiar with the flow. Any help is greatly appreciated!

Authorization Basic should be Base64(client_id:client_secret)

Related

Twitch API's request data always empty on specific route and only on browser

Summary
I am building a website(react app) integrated with twitch helix api.
I use the Implicit grant flow to auth my website
When request this https://api.twitch.tv/helix/videos route with game_id query param, it will always return an empty array
a picture from edge browser's network and console I printed
And the other routes are works fine.
like this route
https://api.twitch.tv/helix/games/top
or same route with id query param
https://api.twitch.tv/helix/videos
BUT I use the api tester like Thunder Client for VS Code.
The https://api.twitch.tv/helix/videos works fine
Also used the C# NET6 ConsoleApp to test on my windows 11
Found that this https://api.twitch.tv/helix/videos route only works on server side, the client side could not works.
Only this https://api.twitch.tv/helix/videos route with game_id query param return an empty array while others (same api with different route or same route with other query param) works fine, it seems this is not a CORS error
Tried Solution
Had tried this CORS - Wrong ‘Access-Control-Allow-Origin’ header on twitch developer forums to add a request header 'accept': 'application/vnd.twitchtv.v5+json', or renew my twitch developer console's clientId.
But still didn't work
My website on vercel
Does anyone know this issue or I am missing something?
Try set language request header to a empty string:
headers.set('accept-language', '')
It worked for me.

Access and Refresh Tokens

I am using caspio rest api to authenticate my users in a mobile app. Upon authenticating, I was given an access token to which I included in my AJAX call under the parameter 'Authorization' : Bearer [access token].
I understand that I can renew the token with the refresh token given to me where I can use the POST call.
My question is: prior to using the POST call for a new token, must I store the access token?
Also, the Caspio website advised this format for the POST call:
Method: POST
URL: Token Endpoint
Body: grant_type=refresh_token&refresh_token= [token value]
Header parameters:
Authorization: Basic [string "Client_ID:Client_Secret" encoded in Base64]
Content-Type: application/x-www-form-urlencoded
Should I also include the client ID and client secret in the parameters? Upon using Firefox's rest client, I'm getting a bad request (400) error.
Thank you for the help!
I never using caspio rest api before. The answer base on my OAuth experiences.
My question is: prior to using the POST call for a new token, must I store the access token?
YES! The OAuth 2.0 using the access token to switch the refresh token at first time.
Should I also include the client ID and client secret in the parameters? Upon using Firefox's rest client, I'm getting a bad request (400) error.
According to the api document. You should include the client ID and client secret in your request, like most OAuth 2.0 do.
The bad request (400) error you may see the rfc6749 to find further information.

Hide JWT token in Javascript

I've implemented a JWT authentication for my rest api.
I'm struggling to understand how to hide the token in JavaScript.
For example, all the clients (web browser and mobile phone app) will call my api with an header:
Authorization': 'Bearer eyJ0eXAiOXXXXXXX
In PHP it makes sense, but in JavaScript "everyone" can see the token. So what's the point of having one?
Even if the token expires after X minutes, all you need to do is get the new token every X minutes, and you have access to the same API.
Did I miss something?
Of what I have understand of Token, they are used to help the server to know 'who is sedding this request' and if this person has the right to.
they are made for simplification of this process, not for security.
If you don't use Token, I think, that means you have to send and check password at each request.
But yes, the information inside is not hidden, as you read Here:
Do not put secret information in the payload or header elements of a JWT unless it is encrypted
I know that you can encrypt your token, but I've never done this, so I can't say much about it.
A solution is using SSL/HTTPS for security.

Gmail API - sending email with oAuth2.0 in javascript

I'm trying to create a web page that sends an email only using javascript and Gmail API. I have set up my developer's console to use the API and also created an API key and a credential.
I have adapted this example code, and so far I think I got to the point of loading the GMail API. (or.. 400 means something is wrong?) The console log shows:
POST https://content.googleapis.com/gmail/v1/users/me/messages/send?alt=json 400 (OK)
zu # cb=gapi.loaded_0:85
n # cb=gapi.loaded_0:85
Cu # cb=gapi.loaded_0:85
(anonymous function) # cb=gapi.loaded_0:86
g # cb=gapi.loaded_0:55
c # cb=gapi.loaded_0:46
And when I try authenticating with oAuth2.0 through a url:
var code;
$.get("https://accounts.google.com/o/oauth2/auth?scope=email&
redirect_uri=http://hiro.collegewebserver.com/COSW200/hw13/gmailtest.html&
response_type=token&client_id=386373199858-o1rt7qj3gt99gbfg6pqpr0g6i92urq9t.apps.googleusercontent.com&
approval_prompt=force",
function (returnedValue) { code = returnedValue; });
I get this message:
XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/auth?scope=email&
redirect_uri=http://h…3gt99gbfg6pqpr0g6i92urq9t.apps.googleusercontent.com&
approval_prompt=force.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://hiro.collegewebserver.com' is therefore not allowed access.
I've read other posts that say this may be due to cross origin requests being blocked? Someone wrote that there are ways to work around this like using JSONP?
If someone can enlighten me as to what I'm missing here, I would really appreciate! :)
You cannot make an ajax call to Google to get your access code. The idea of OAuth2 is that you first redirect the user to accounts.google.com/o/oauth2/your_settings. In your case:
https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=http://hiro.collegewebserver.com/COSW200/hw13/gmailtest.html&response_type=token&client_id=386373199858-o1rt7qj3gt99gbfg6pqpr0g6i92urq9t.apps.googleusercontent.com&approval_prompt=force
In this Google environment the user can login with his/her account. One of the settings you provide is the redirect_uri.
Since you whitelisted http://hiro.collegewebserver.com/COSW200/hw13/ as one of the Authorized redirect URIs in your Google Developers Console and this url is related to your client_id, no other application than your website can use your client_id to receive an authorization code.
After login the user will be redirected to this redirect_uri, with the code as one of the parameters.
This will look something like this:
http://hiro.collegewebserver.com/COSW200/hw13/#access_token=yb27…jK0AVtilhnrJDcuTISgIB5LiNtKLMut1kVvPW69w&token_type=Bearer&expires_in=3600
After that you would have to extract the access token from the url. With this access token you can authorise the user and make use of the scopes you entered. This can be done with an ajax call.
$http({
method: 'GET',
url: 'https://www.googleapis.com/upload/gmail/v1/users/userId/messages?access_token=' + access_token
}).then(function(response){
//your code
})
You could also put the access_token in the header of the call:
Authorization: Bearer access_token
Another option is to use the API Client Library for JavaScript (Beta): https://developers.google.com/api-client-library/javascript
Although it is in Beta and the basic workflow is the same, it might give you clearer examples.

Google OAuth2 - Exchange Access Code For Token - not working

I am currently in the process of implementing a server-side OAuth2 flow in order to authorize my application.
The JS application will be displaying YouTube Analytics data on behalf of a registered CMS account to an end user (who own's a channel partnered with the CMS account). As a result of this, the authorization stage needs to be completely hidden from the user. I am attempting to authorize once, then use the 'permanent' authorization code to retrieve access tokens as and when they're needed.
I am able to successfully authorize, and retrieve an access code. The problem begins when i attempt to exchange the access code for a token.
The HTTP POST Request to achieve this needs to look like this...
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
I am using this code to achieve this:
var myPOSTRequest = new XMLHttpRequest();
myPOSTRequest.open('POST', 'https://accounts.google.com/o/oauth2/token', true);
myPOSTRequest.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
myPOSTRequest.send('code=' + myAuthCode + '&redirect_uri=http%3A%2F%2Flocalhost%2FCMSAuth3.html&client_id=626544306690-kn5m3vu0dcgb17au6m6pmr4giluf1cle.apps.googleusercontent.com&scope=&client_secret={my_client_secret}&grant_type=authorization_code');
I can successfully get a 200 OK response to this Request however no access token is returned, and myPOSTRequest.responseText returns an empty string.
I have played with Google's OAuth Playground - and can successfully get a token using my own credentials.
Am i missing something here?
You cannot do this, because there is the same origin policy. This is a security concept of modern browsers, which prevents javascript to get responses from another origin, than your site. This is an important concept, because it gives you the ability, to protect you against CSRF. So don't use the code authorization flow, use instead the token authorization flow.
Try and build up the full URL. Then dump it in a webbrowser. If its corect you will get the json back. You have the corect format.
https://accounts.google.com/o/oauth2/token?code=<myAuthCode>&redirect_uri=<FromGoogleAPIS>&client_id=<clientID>&client_secret={my_client_secret}&grant_type=authorization_code
Other things to check:
Make sure that you are using the same redirect_uri that is set up in google apis.
How are you getting the Authcode back? If you are riping it from the title of the page i have had issues with it not returning the full authcode in the title try checking the body of the page. This doesnt happen all the time. I just ocationally.

Categories