Axios : put on hold requests - ajax

I have the following axios interceptor.
It checks the validity of the stored token. If not valid, a request is fired to retrieve and store the refreshed token.
axios.interceptors.request.use(async config =>
if(checkValidity(localStorage.getItem('token')) === false) {
const response = await axios.get('http://foobar.com/auth/refresh');
localStorage.setItem('token', response.headers['token']);
config = getConfigFromResponse(response);
}
return config;
});
It works great. The problem is that if I have many requests with invalid token then many requests to http://foobar.com/auth/refresh are done to refresh it.
Is it possible to put all the requests in an array and fire them after when the refresh is done ?
The idea is to avoid catching 401 errors and replaying the request : this is why I want to "save" the requests while the token is being retrieved and then fire them when the token is ready.

Related

Spring Keycloak Adapter sometimes returns with "Token is not active" when uploading files

lately we are facing an issue that our Spring Boot backend service (stateless REST service) SOMETIMES returns an HTTP 401 (Unauthorized) error when users try to upload files >70 MB (or in other words, when the request takes longer than just a couple of seconds). This does not occur consistently and only happens sometimes (~every second or third attempt).
The www-authenticate header contains the following in these cases:
Bearer realm="test", error "invalid_token", error_description="Token is not active"
Our Spring (Boot) configuration is simple:
keycloak.auth-server-url=${KEYCLOAK_URL:http://keycloak:8080/auth}
keycloak.realm=${KEYCLOAK_REALM:test}
keycloak.resource=${KEYCLOAK_CLIENT:test}
keycloak.cors=true
keycloak.bearer-only=true
Essentially, our frontend code uses keycloak-js and does the following to keep the access token fresh:
setInterval(() => {
// updates the token if it expires within the next 5s
this.keycloak.updateToken(5).then((refreshed) => {
console.log('Access token updated:', refreshed)
if (refreshed) {
store.commit(AuthMutationTypes.SET_TOKEN, this.keycloak.token);
}
}).catch(() => {
console.log('Failed to refresh token');
});
}, 300);
Further, we use Axios and a respective request filter to inject the current token:
axios.interceptors.request.use(
(request: AxiosRequestConfig) => {
if (store.getters.isAuthenticated) {
request.headers.Authorization = 'Bearer ' + store.getters.token;
}
return request;
}
);
This worked very well so far and we have never experienced such a thing for our usual GETs/POSTs/PUTs etc. This happens only when users try to upload files larger than (around) 70MBish.
Any hint or tip how to debug this any further? We appreciate any help...
Cheers

Laravel Sanctum with SPA: Best practice for setting the CSRF cookie

Currently, my SPA is simple and has only a contact form. The form data is sent to the backend. I have installed Laravel Sanctum for that.
axios.get('/sanctum/csrf-cookie').then((response) => {
axios.post('api/contact')
.then((response) => {
//doing stuff
});
});
This works perfectly fine. However, I was wondering. Where and which time in your SPA do you fire the initial request to get the CSRF cookie? (axios.get('/sanctum/csrf-cookie'))
My first thoughts were:
Every time the page is mounted/loaded
Only when you receive a 419 and you attempt to refresh the token and retry the previous request
You don't fire any API requests, only when the user tries to log in and only then you are requesting a cookie (in my case I don't have any user authentification)
For each API request, you wrap it with axios.get('/sanctum/csrf-cookie') around
So for future readers, I chose:
Only when you receive a 419 and you attempt to refresh the token and retry the previous request
For that, I'm using the package axios-auth-refresh.
My settings look like that
//bootstrap.js
import axios from 'axios';
import createAuthRefreshInterceptor from 'axios-auth-refresh';
axios.defaults.withCredentials = true;
axios.defaults.baseURL = process.env.GRIDSOME_BACKEND_URL;
const refreshAuthLogic = (failedRequest) => axios.get('/sanctum/csrf-cookie').then((response) => Promise.resolve());
createAuthRefreshInterceptor(axios, refreshAuthLogic, { statusCodes: [419] });
window.axios = axios;

Dealing with axios interceptors when sending many ajax requests

I use Larave+JWT and vue2 + vuex2 + axios
So when user logins I store auth token in vuex store. When the token expires I need to refresh it. In order to refresh it I need to send the same token to /refresh route, and get a new token. At least that's how I got it and actually it works.
The problem is that interceptor catches 401 responses and tries to refresh token, but what if, say, in my component I send many requests with expired token? Since ajax requests are async, the interceptor code runs many times. So I got many refresh requests. Once the initial token is refreshed it is not considered valid. When interceptor tries to refresh invalid token server responds with error and I redirect to login page.
Here is the code:
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true
axios.post('auth/refresh').then((response) => {
let token = response.data.token
store.dispatch('auth/setAuthToken', token)
let authorizationHeader = `Bearer ${token}`
axios.defaults.headers = { 'Authorization': authorizationHeader }
originalRequest.headers['Authorization'] = authorizationHeader
return axios(originalRequest)
}, (error) => {
store.dispatch('auth/clearAuthInfo')
router.push({ name: 'login' })
})
}
return Promise.reject(error);
});
I think you'll have to change your approach on how you refresh your token. Leaders like Auth0 recommends proactive periodic refresh to solve this problem.
Here is a SO answer where they talk about it.
Set the token expiration to one week and refresh the token every time the user open the web application and every one hour. If a user doesn't open the application for more than a week, they will have to login again and this is acceptable web application UX.

Can Ajax make a Cross-Origin Login?

I'm trying to login from one of my servers to another in order to send cross-origin requests that requires being logged. is it possible?
I have two web servers, A and B. Lets say www.a.com and www.b.com.
B has an API that can be used only if the client is logged in. I need to use that API from A clients.
So, I send from A client an ajax (post) login request to B. B responses with CORS headers, the session cookie and a successful redirection to B's home/index.
But when I make a second ajax request (jsonp request) from A client to B server, this request doesn't send the previous session cookie received, therefore the login request failed.
If I login to www.b.com manually (in a second browser tab), all requests from A to B are successful detected as a logged user, so, the B API works from A.
I think that the session cookie received from my login requests is not being saved to the browser.
This is my login request:
$.post("www.b.com/login", { 'j_username': 'username', 'j_password': 'password' } );
Using:
jqXHR.withCredentials = true;
settings.crossDomain = true;
Response headers:
Access-Control-Allow-Headers:x-requested-with
Access-Control-Allow-Methods:POST, GET, OPTIONS
Access-Control-Allow-Origin:*
...
Location:http://www.b.com/home
...
Set-Cookie:JSESSIONID=tY++VWlMSxTTUkjvyaRelZ0o; Path=/
The cookie received is being saved to www.a.com or to www.b.com? How can I set this cookie to www.b.com from an A client ajax request? I think that is the problem.
As apsillers said, we can't use the wildcard Access-Control-Allow-Origin:*.
But this doesn't solved the problem.
I was setting jqXHR.withCredentials = true; inside a beforeSend handler function.
$.post({
...
beforeSend: function(xhr) {
xhr.withCredentials = true;
},
...
});
And for some reason, this doesn't work. I had to set the use of credentials directly:
$.post({
...
xhrFields: {
withCredentials: true
},
...
});
This code works perfectly !
Thanks you.

Google OAuth: can't get refresh token with authorization code

I am using Google API Client for Google Analytics with OAuth 2.0
I read this to get the refresh token but it doesn't appears: https://developers.google.com/identity/protocols/OAuth2WebServer#offline
I only get this instead:
{
"access_token": "ya29.twHFi4LsiF-AITwzCpupMmie-fljyTIzD9lG8y_OYUdEGKSDL7vD8LPKIqdzRwvoQAWd",
"token_type": "Bearer",
"expires_in": 3599,
"id_token": "very long string"
}
Here is the code:
Javascript (to get the Authorization Code): that works
gapi.analytics.ready(function() {
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: '257497260674-ji56vq885ohe9cdr1j6u0bcpr6hu7rde.apps.googleusercontent.com',
});
gapi.analytics.auth.on('success', function(response) {
var code = response.code;
$.ajax({
url: "getTokensFromCode.php",
method: "GET",
data: {
"code": code
},
success: function (tokens) {
// I can't get refresh token here, only get "access_token" and "id_token"
console.log(tokens);
}
});
});
});
PHP (to exchange Authorization Code for tokens): that doesn't work
// I get the authorization code in Javascript
$code = $_GET['code'];
$redirectURI = "postmessage";
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectURI);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->authenticate($code);
$tokens = $client->getAccessToken();
echo $tokens;
I need the refresh token in Javascript, that's why I get the authorization code in Javascript and make an Ajax request to get the refresh token.
You will only get the refresh_token the very first time that a user grants access to your app. You'll need to store the refresh_token somewhere to be able to use it afterwards. You won't get a new refresh token the next time a user logs in to your app.
FWIW: using a refresh token in a Javascript client doesn't make a lot of sense since a Javascript client can't store it in a safe (confidential) way. Since Javascript clients live in browsers and users are present in browsers, you can just redirect the browser to the authorization endpoint again and you'll get a new access token (which is also the purpose of a refresh token). The SSO session for the user at Google will make sure that the user doesn't need to login again and that the experience is seamless.
Check out this response by #curious_coder
Google API Refresh Token
He explains a way to get the Refresh Token every time :) Life saver. This post helped me get there so I figured I'd share this for any one else trying to find their refresh token. Add the last two lines of this code to your Auth process
$client = new Google_Client();
$client->setAuthConfigFile(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessType('offline'); //To fetch refresh token(Refresh token issued only first time)
$client->setApprovalPrompt('force'); //Adding this will force for refresh token
Also I used var_dump($tokens) to get the contents instead of echo. Dont remember if it makes a difference in PHP but $tokens will be an array of objects.

Resources