I Have a WebPage That USE AWS API Gateway using AWS-Cognito Authentication. Most of the Buttons in Web Page Call Api and send or Retrieve data. This is the Code I Use Under Every Button Click
getAuthenticateUser().getSession(function(err,session){
if (err) {
console.log("Error"+err);
return;
}
if(session.isValid())
{
$.ajax({
url: URL,
headers:
{
'Authorization':session.getIdToken().getJwtToken(),
'Content-Type':'application/json'
},
method: 'GET',
dataType: 'json',
success: function(data){
// Execute Function Need to Execute on Success
}
,
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
if(!session.isValid())
{
console.log("Session is not valid..!");
//Please Login to Continue
}
});
This is Working Fine without Issue.But the Problem is It take Some Time to Execute it Everytime and Feeles like every time it Gives a New Session for Each call even Previous Session is not Expired. How can I Use get new Session Only when it Expired and if Previous Session is not Expired just check the validity of it globally and get a new Authorization Header Only I need..?
Because In My Code Once User Press One Button and Send Data id same User press another button after 30 sec i'm getting new session again right ..? it really gives me really bad on web site Performance.
Any Idea How to Solve this ..?
this my getAuthenticationUser() Code
function getAuthenticateUser()
{
return userPool.getCurrentUser();
}
and this my Global Variable in that Javascript page
var poolData = {
UserPoolId : 'usXXXXXXXXXXOv3jSL',
ClientId : 'XXXXXXXXXXka8g'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
getSession() does not create a new session if the current session is valid.
If the current session is either null or invalid, it tries to refresh the session (using the refresh token) to get the ID token that is necessary to successfully complete the HTTP request using the Authorization header. Otherwise, it throws an error requesting to authenticate.
You can see what getSession() exactly does by taking a look at the CognitoUser class definition. (currently on line 1016.)
Related
I have a view in my django backend called getUserInfo that will return the user's info as json format.
This is my view:
#api_view(["POST"])
def getUserInfo(request):
if request.user.username:
serial = userInfoSerializer(request.user)
return Response(serial.data)
else:
return Response({"notLoggedIn": True})
When I'm not logged in ajax request are working ok but when I login to a user account I get an "forbidden" error and it says csrf validation failed. I am also refreshing the csrf token every time the user logs in or out.
So it should work but it is not working.
This is my ajax request:
function login(){
getcsrf();
$.ajax({
url: '/api/login/',
type: 'POST',
headers: {
"XCSRF_TOKEN": csrf
},
data: {
username: $("#l-username").val(),
password: $("#l-password").val(),
},
})
.done(function(data) {
console.log(data)
if(data.msg){
console.log(data.msg)
$(`<div class="p-2 bg-danger">`+data.msg+`</div>`).prependTo('#message-box')
}else{
getcsrf();
getUserInfo();
}
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
The function getcsrf refreshes the global variable containing the csrf-token value called "csrf" and then I send my ajax request. After the request I refresh it again. I'm sure the value of csrf token changes every time I am refreshing it when user logs in or out but server always says "forbidden".
I have inserted this code in my settings.py file:
CSRF_HEADER_NAME = "HTTP_XCSRF_TOKEN"
and I am sending ajax request with a header called XCSRF_TOKEN
Can any one help me?
SORRY FOR MY ENGLISH
Maybe try:
headers: {
"HTTP_XCSRF_TOKEN": csrf
},
so that it matches the header name in your settings file.
okay let me answer it my self.
i cleared my browser cookies and then it worked properly
I have a webapp that its backend is written in Python and renders some html for the frontend users.
What I would like to achieve is:
when a user makes a POST request to /token, the backend replies with a JSON document {"access_token": access_token, "token_type": "bearer"}; this is already in place
after the above takes place, every subsequent request / navigation to the webapp, should set a header named Authorization equal to Bearer <access_token> to every GET, POST, etc. request that it does; not important for the time being
can you advise and describe how to maintain a single variable client-side called access_token that its default value is null, but when doing POST to /token, then the variable access_token is initialised and never changes through navigation, unless the end user makes another POST request to /token again to reset the access_token to the new value ?
I am not familiar with jQuery or javascript much. Can you suggest how to initialise, set, reset a variable (and just print it, for example, using console.log) based on the background information above ?
You can store the token in local storage, or in cookies, either would work. Then, when you go to make an ajax call, you'll retrieve the value from whichever you used, and add it to the outgoing ajax request. How exactly you do that willl depend on what specific ajax implementation you use. For example google "add auth token to jquery.ajax" and you'll find the right syntax for that library
Something like this would work:
// do initial login and get token
var token = response.access_token;
// store it in local storage
localStorage.setItem('apiKey', token);
// ... navigate around and what not...
// later, when you need to make another call, get the token
var token = localStorage.getItem('apiKey');
$.ajax({
url: url,
method: "POST",
dataType: "json",
//.. other props as needed...
beforeSend: function (xhr) {
/* set the Authorization header with the token */
xhr.setRequestHeader("Authorization", "Bearer " + token);
},
success: function (data) {
// do something cool with data
},
error: function (jqXHR, textStatus, errorThrown) {
// handle errors ...
}
});
I have a website that basically makes API calls and displays the data in a table; the API is on a different server from the website.
If the API server is down what is the best way to alert the user client-side (JavaScript) that the server is unavailable?
Could/Should I put the alert in the API call error handling (See code for example)? What is the best practice for this type of situation.
function apiCall(query, product){
var p = product;
var urlr='https://myFakeAPIUrl/api/'+query+'/'+ product;
$.ajax({
contentType: 'application/json',
crossDomain: true,
url: urlr,
type: "GET",
success: function (result){
alert("Yay, the API server is up.");
},
error: function(error){
console.log(error);
alert("Sorry, the server is down.");
}
});
}
var productData = apiCall("Produce", "112233");
I would ask myself what a user would like to see in this situation.
What I always do is putting a timeout on the Ajax request, whenever that timeout of e.g. 9999ms runs out, the user should get notified (with a toast, a heading, etc..) that something went wrong and that they should try it again later.
I am creating a simple web page, that make use of the Google Translation Service.
The page has a field, to receive the input from the user and a button to trigger the call to the Translation API. It returns the result translation to the user.
I've successfully done the flow above using Ajax requests, but the access token
is hard-coded into my method and I want to change that to a call that gets sent whenever the token expires (currently I have to request a new token using the Google CLI and replace it in my code).
I have a very basic knowledge of Oauth2.0 and I've read the Google Documentation but couldn't find a part of it that would tell me the endpoint to call to get an access token from the client-side.
Could someone point me in the right direction, please?
Here is my code:
HTML:
<form id="translate_form">
<input id="input" />
<button id="translate_button">Translate</button>
</form>
Javascript
$("#translate_form").submit(function () {
var text = $("#input").val()
sendTranslationRequest(text);
return false;
})
function sendTranslationRequest(inputText) {
var requestBody = {
q: inputText,
source: "en",
target: "fr",
format: 'text'
}
translationAjaxRequest(requestBody);
}
function translationAjaxRequest(requestBody) {
var access_token = [access_token]
$.ajax({
url: "https://translation.googleapis.com/language/translate/v2",
method: "POST",
contentType: "application/json",
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Bearer " + access_token)
},
data: JSON.stringify(requestBody),
success: function (response) {
var translatedText = response.data.translations[0].translatedText
alert(translatedText)
},
error: function () {
console.log("An error occurred on the request:", response)
}
});
}
The relevant endpoints to get an access token and refresh it are:
https://accounts.google.com/o/oauth2/v2/auth
https://www.googleapis.com/oauth2/v4/token
However, you’ll need to perform several steps in order to get an access token and a refresh token. You may want to review this guide on Using OAuth2.0 for Web Server Applications. It will walk you through the prerequisites, obtaining an access token and refreshing your token.
Alternatively, you may use an API Key. Just be mindful of the recommendations on how to secure it, since a stolen API Key may be used to generate calls that would be charged directly to your billing account.
I'm working on a web page that lets you search for twitter users in your area. You enter a name in the search box and it returns users with that name within 50 miles of the city (the city is always the same).
I was having trouble authenticating, and I found oauth.io. I used that to authenticate and it seems to be working. But when I do a search, my request to Twitter returns as a 400 bad request error. I'm not sure what I'm doing wrong. I've looked at the oauth.io documentation but couldn't find anything.
Here is the part of the code that gets the value of what the user entered into the form field:
// Click function
$('.user-getter').submit(function(event) {
// prevent form refresh
event.preventDefault();
// zero out results if previous search has run
$('.user-results').html('');
// Get the values of what the person entered in search
var query = $(this).find("input[name='user_search']").val();
// Run function to send API request to Twitter
getUser(query);
}); // end click function
Here is the part of the code that calls the authorization and then sends the ajax request:
var getUser = function(query) {
OAuth.initialize('oMQua1CuWerqGKRwqVkzDx5uijo')
OAuth.popup('twitter').done(function(twitterData) {
$.ajax({
type: "GET",
url: "https://api.twitter.com/1.1/users/search.json?&geocode=42.94003620000001,-78.8677924,50mi&q=" + query,
dataType: "jsonp"
});
console.log( "Data Saved: " + twitterData ); // can see in inspector tab under Network
}); // end oAuth popup
};
Right now, I just want to see the result in console.log.
To make a request to Twitter API using OAuth.io you have to use the OAuth.io Javascript SDK instead of directly $.ajax (the OAuth.io Javascript SDK use the syntaxe of $.ajax behind the scene)
OAuth.initialize('oMQua1CuWerqGKRwqVkzDx5uijo')
OAuth.popup('twitter').done(function(twitterData) {
twitterData.get('/1.1/users/search.json', {
data: {
q: query
}
}).done(function(search) {
//result of the search here
console.log(search);
}).fail(function(error) {
//error management here
});
})
The SDK does all the hard things for you transparently: proxy the HTTP request, inject all the needed OAuth credentials (oauth_token, oauth_token_secret, signature, nonce, timestamp etc..)
Take a look to this jsfiddles: http://jsfiddle.net/uz76E/10/
I hope that helps,