Symfony2 send back login form on each AJAX request - ajax

I'm doing a back-office image upload form using Symfony 2.5.12 (yeah I know I'm a little out of date, but I will work on that soon :)). I want to upload the images via AJAX, but I get a 302 redirect to the login form on every AJAX request I send.
Here is the JS part on my stuff (it is simplified because for the moment I just want to do a successful AJAX call without 302 redirect to the login page, so I deleted the data related stuff) :
form.addEventListener('submit', event => {
event.preventDefault();
const url = form.getAttribute('action'); // '/admin/uploadImage'
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
});
And here is my action in my controller, bound to /admin/uploadImage URL :
public function uploadAction() {
return new JsonResponse(array('test' => 'hello world'));
}
Every /admin URL requires ROLE_ADMIN role, I defined it in security.yml :
security:
#...
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
This way, it is normal that a login form shows when I want to access to this kind of URL. But when I trigger my AJAX call, I'm already logged in because I'm on /admin/gallery page.
Does anybody can figure out what is wrong with what I'm doing ?
Thank you very much.

I absolutely don't know why, but it seems the issue was related to whatwg-fetch fetch implementation. I replaced it with axios and the problem is gone.

Related

Cypress cy.visit() is not redirecting to correct URL

I am trying to bypass the UI login by using cy.request() to log a user in and cy.visit() to go to the restricted route. I have followed this doc: https://docs.cypress.io/guides/end-to-end-testing/testing-your-app#Bypassing-your-UI
However, the test fails because the visit URL ('http://localhost:3000/join-or-create') is not loaded and instead the home page URL is loaded (http://localhost:3000/).
This is my test code:
describe('when user is signed in but has not joined a group', () => {
beforeEach(() => {
cy.request('POST', 'http://localhost:5000/api/testing/reset');
const user = {
name: 'Joe Bloggs',
email: 'Joe#Bloggs.com',
password: 'Password',
};
cy.request('POST', 'http://localhost:5000/register', user);
cy.request('POST', 'http://localhost:5000/sign-in', user);
cy.visit('http://localhost:3000/join-or-create');
});
it.only('should allow a logged in user to join or create a group', () => {
cy.contains('Join a group');
cy.contains('Create a group');
});
});
If I change cy.contains('Join a group'); to cy.contains('Welcome'); (which is content on the URL 'http://localhost:3000/') then the test passes.
If I use:
cy.visit('http://localhost:3000');
cy.get('[data-testid="email"]').type('Joe#Bloggs.com');
cy.get('[data-testid="password"]').type('Password');
cy.contains('sign in').click();
instead of cy.visit('http://localhost:3000/join-or-create'); the test passes.
The output of the test body shows that is redirecting to a new URL 'http://localhost:3000/' (as shown in the screenshot below) but I can't figure out why.
Thanks for any help.
In the bypass code, check the response from the POST request
cy.request('POST', 'http://localhost:5000/sign-in', user)
.then(response => console.log(response))
to see what tokens are returned.
Then in the form-login code, look at what happens to the same token after cy.contains('sign in').click() and see where the browser stores same token.
That's probably the step missing in the bypass code. You'll need to add something to do the same, e.g
cy.request('POST', 'http://localhost:5000/sign-in', user)
.then(response => {
const token = response.body.token; // figure out where the token is in response
cy.setCookie(token); // figure out where the app want's the token
})
It's also difficult to tell from the question what URL you need to cy.visit() in the bypass code, but there's only a couple of them so try both permutations.

Spring security does not redirect after successful login authentication

I am using spring security + thymeleaf to recognise my css and javascript files. These css and javascript files make up my front end login page, and for special reasons, my login form is within a js file and i include this file in my main html file. To authenticate the login credentials, a custom /POST request needs to be called using javascript like below. This function below executes when the form submit button is pressed.
function submitForm() {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("username", "<removed>");
urlencoded.append("password", "<removed>");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("http://localhost:8080/userAuth", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
Controller to handle successful login end point
#Controller
public class LoginSuccessController {
#GetMapping("/login_success")
public String success() {
return "success";
}
}
On the browser, I can infer that authentication is successful and there is something that happens related to my successful login endpoint. However, my browser remains at localhost:8080/login and does not redirect to the login_success endpoint. I am unable to figure out why so. Any help is much appreciated.
Browser network activity after submit button
because you use ajax. if you check networks tab I believe you will see response ans 301/302 with Location header.
Edit: you have to either use plain html form or redirect manually from js side
Edit 2:
fetch("http://localhost:8080/userAuth", requestOptions)
.then(response => response.text())
.then(result => {
// do some stuff with response
location.href = '/my-success-page-after-login'; // <- here is redirect
})
.catch(error => console.log('error', error));
Explanation: the problem is that browser doesn't follow redirect response for AJAX calls. Ajax call will just return you a response from server(redirect with 301/302 status code in your case) but this will NOT make browser to follow that redirect

How to use Auth::check or Auth::user between different domains?

I've got a question regarding Laravel framework (vers. 5.2) and the authentication. I have 2 domains which represent a software. let's call them https://azure.mydomain.com and https://azuresoftware.mydomain.com.
The Laravel application is hosted on the domain https://azuresoftware.mydomain.com. https://azure.mydomain.com is just a CMS framework which is providing some information about the website.
Now I want to display different menus, if the user is logged in or not on https://azure.mydomain.com. I thought, I can do a fetch request to https://azuresoftware.mydomain.com/ and use the Laravel methods Auth::check() to check if the user is already logged in or not. I know that this is a CORS fetch request, but this is not the issue. I've allowed in the IIS webserver requests from https://azure.mydomain.com. The request works fine and also just a simple request. But actually Auth::check() is always returning false, even when I'm logged in on the software side.
This is my code so far:
<script>
fetch('https://azuresoftware.mydomain.com/checkLogin', {
method: 'GET',
headers: {
'Content-Type': 'text/plain'
}
})
.then(function(res) {
return res.json()
})
.then(function(data) {
if(data.isLoggedIn) {
// do some stuff...
}
else
{
// do some other stuff...
}
});
</script>
routes.php:
Route::group(['middleware' => 'web'], function () {
...
Route::get('checkLogin', function() {
return json_encode(['isLoggedIn'=>\Auth::check()]);
});
...
I'm sure, I forgot something essential, why it is not working this way.
This is due to the fact that AJAX calls only send cookies if the url you're calling is on the same domain as your calling script.
See Cross domain POST request is not sending cookie Ajax Jquery for more information.

Can't use fetch api in laravel, redirect login page

I'm trying to use fetch api with laravel, but the request goes to the login url, not the given url.
for example;
route
//also this route group has auth and admin middlewares (checks user is authenticated and is admin)
Route::delete("media/delete/{id}", ["as" => "admin.posts.media.delete", "uses" => "AdminController#deletePostMedia"]);
ajax
fetch("../../media/delete/" + id, {
method: "DELETE",
headers: new Headers({
"X-CSRF-TOKEN": document.head.querySelector("[name=csrf-token]").content
})
})
it gives me the below error:
DELETE http://commerce.test/login 405 (Method Not Allowed)
as you can see above, the request goes to login url, not given url..
How can I fix this?
Laravel by default includes axios for ajax requests and it's very easy to use, have a look here.
In your example you'd write something like this:
axios.delete('/media/delete/' + id)
.then(response => {
console.log(response.data);
})
.catch(error=> {
console.log(error);
});

Bypass UI Login using Cypress

I am having problem bypassing UI login. My web application doesn't use API to authenticate users. There are no endpoints like /login. index.php will just open the login page and submit the form to login.
The application authenticate the user by
auth($_REQUEST['username'], $_REQUEST['password_tx']);
This is what cypress printed after UI login submit.
I have no idea how to move on from here.
// This doesn't work. The application doesn't get the user details from the body. It is in the submitted form.
cy.request({
method: 'POST',
url: '/index.php?p=sys001',
form: true,
body: {
username: 'user',
password_tx: 'pass'
}
})
This is the complete testcase for the issue. Added comments to make them understandable.
it("login via form spoof", () => {
cy.get("div#mDiv > form").invoke("attr", "action").then(($action) => { //get
the attribute of 'action' and pass encoded uname and pwd to it
let username = Cypress.env("username");
let password = Cypress.env("password");
cy.intercept("POST", $action, (req) => { //post request and populate body
// intercepting the POST form to spoof it.
req.body = $action + encodeURIComponent(username)+ encodeURIComponent(password)
})
.as("loginForm"); //alias
});
cy.get("div#mDiv > div.login > form")
.submit(); //Submit the form after locating it.
});

Resources