Symfony : Access-Control-Allow-Origin ('security.token_storage) - symfony

I work with Symfony and I try to get the user id from another website (ajax). But it does not works !
I have this error in my browser :
Access-Control-Allow-Origin
My code is :
$response->headers->set('Access-Control-Allow-Origin', '*');
/* That does not works and returns : 'NOOOO !!!' but, no error */
if($this->get('security.authorization_checker')->isGranted('ROLE_USER'))
{
$usertosend = $this->get('security.token_storage')->getToken()->getUser();
$id = $usertosend->getId();
$response->setData(array('user'=>$id));
}
else
{
$response->setData(array('user'=>'NOOOO !!!'));
}
/* That works :*/
$usertosend = $this->get('security.token_storage')->getToken()->getUser();
/* That does not works and returns : Access-Control-Allow-Origin error*/
$id = $usertosend->getId();
As soon as I use a getter of the user, there is an error.
If I don't use the getter, there is no error.
There is no problem with the origin domain.
Ok, The problem came from the cookies. So I add these headers :
$response->headers->set('Access-Control-Allow-Origin', 'http://localhost');
$response->headers->set('Access-Control-Allow-Methods', 'get');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, *');
And I add this mention in my ajax method :
xhrFields: {withCredentials: true},
$.ajax({
type: 'get',
url: 'http://myurl.com',
xhrFields: {withCredentials: true},
success: function(user){
alert(user.user);
}
I hope, it will help next users.
Thanks for your help :)
See you

You can use NelmioCorsBundle in your symfony project for adding headers CORS in they response of your application.
This is a very simple and quickly installation. This is a standard bundle for construct a symfony API Rest Application which called with external application.
NelmioCorsBundle

Related

How to create a firebase dynamic link with the REST API

I'm trying to generate a dynamic link in firebase using the REST API. I've tried following instruction on the following page of the documentation: https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_parameters
My apologies in advance for bad formatting, but my request looks something like this:
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=
with headers:
Content-Type: application/json
and body:
{
"dynamicLinkInfo":{
"domainUriPrefix":"https://<myDomain>.page.link/",
"link":"https://www.google.com/",
"androidInfo":{
"androidPackageName":"com.<companyName>.<appname>"
}
}
}
The response i get is:
{
"error": {
"code": 400,
"message": "Invalid Dynamic Link domain: '' or Domain Uri Prefix: 'https://<myDomain>.page.link/'. Expecting exactly one. Dynamic Link Domain isPresent = false, Domain URI prefix isPresent = false, [https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_parameters]",
"status": "INVALID_ARGUMENT"
}
}
My firebase project has a the .page.link domain registered within the project. In the dynamic links section of the firebase project it does show up. I've tested creating links in the firebase console and i've even been able to manually make dynamic short-links using the react-native-firebase package so i'm pretty sure nothing is wrong with my project.
You cannot have / at the end of domainuriprefix. Can you try removing it?
I want to add another solution.
In my case a simple white space in front of 'https' was the trigger.
"message": "Invalid Dynamic Link domain: '' or Domain Uri Prefix: ' https://[...]'
You do need to add the https:// portion to your domainUriPrefix ->
{
"dynamicLinkInfo":{
"domainUriPrefix":"<myDomain>.page.link",
"link":"https://www.google.com/",
"androidInfo":{
"androidPackageName":"com.<companyName>.<appname>"
}
}
}

Error while instanciating Restivus "Cannot find name 'Restivus' "

I imported restivus using :
meteor add nimble:restivus
And while using Restivus I encounter this error on meteor startup :
"Cannot find name 'Restivus' ".
I can although GET requests but I wonder if it impacts the behavior of the app.
Here is the code used :
if (Meteor.isServer) {
// Global API configuration
var Api = new Restivus({
apiPath: 'api/',
prettyJson: true
});
}
When receiving POSTs my request.body and my bodyParams are empty :
Api.addRoute(':id/test', {
post: function () {
var id = this.urlParams.id;
console.log("Body contains : ");
console.log(this.bodyParams);
return {
status: 'success',
url : 'post test from id: '+id,
body : this.bodyParams
};
}
});
Does anyone know how to make this error disappear and if this is linked to the POST body problem ?
If you use Meteor 1.4+ you can try to import Restivus to your file with something like this:
import Restivus from 'nibmle:restivus';
The problem with post body being empty was caused by the request I made :
I wasn't specifying the Content-type header.
Once I specified the "Content-Type": "application/json" it worked.
The "Cannot find 'Restivus' " Error is still here though.
Your code looks ok. Here is some code from a server-only file that I am using:
// Global API configuration
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true,
apiPath: 'restAPI/',
defaultHeaders: { 'Content-Type': 'application/json;encoding="UTF-8"' }
});
// Generates: GET, POST on /api/items and GET, PUT, DELETE on
// /api/items/:id for the Items collection
Api.addCollection(Policy);
Perhaps you should move your code to the server directory? I am on Meteor 1.3.4.

Get POST body data in Silex RESTful API

I am creating a RESTful API using Silex. To test I am using Chrome's "Simple REST Client" addon.
In the addon I set the URL to: http://localhost/api-test/web/v1/clients
I set the "method" to: POST
I leave the "headers" blank
I set the "data" to: name=whatever
In my "clients.php" page I have:
require_once __DIR__.'/../../vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app->post('/clients', function (Request $request) use ($app) {
return new Response('Created client with name: ' . $request->request->get('name'), 201);
}
In the addon, the output shows: "Status: 201" (correct), a bunch of headers, and "Data: Created client with name: " (it should say "Data: Created client with name: whatever"
What am I doing wrong? I also tried: $request->get('name')
Thank you.
Three steps were needed to resolve:
1) In "Simple Rest Client" set the "Headers" to:
Content-Type: application/json
2) Change the "Data" to:
{ "name": "whatever" }
3) In Silex add the code to convert input to JSON, as described at http://silex.sensiolabs.org/doc/cookbook/json_request_body.html:
$app->before(function (Request $request) {
if (strpos($request->headers->get('Content-Type'), 'application/json') === 0) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
});
Then I was able to access the data in my PHP code with:
$request->request->get('name')
Thank you #xabbuh for your help, which led me towards the answer.

Symfony - using twig trans filter on 404 page

I have a 404 error page set up through an event listener triggered by Kernel exceptions:
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($event->isMasterRequest()) {
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
$response = new Response();
$event->setResponse(
$response->setContent($this->templating->render(
'LandingPageBundle:Error:error404.html.twig',
['welcome_url' => $this->router->generate("welcome")]
))
);
}
}
}
kernel.kernel_exception_listener:
class: S\Project\LandingPageBundle\EventListener\KernelExceptionListener
arguments: [ "#router", "#logger", "#translator", #templating ]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
This works, but when I try to use the trans filter on the twig error404.html.twig template, it does nothing. My locale is being set in a cookie and read by an event listener to Kernel Requests, so I tried adding the following to onKernelException:
$request = $event->getRequest();
$locale = $request->cookies->get('_locale');
$request->setLocale($locale);
After that, including {{ app.request.locale }} in the template displayed the correct locale, however, the trans filter does not seem to be picking this up.
It seems like my problem may be related to Symfony 2.1 set locale and yet that question does not quite fit my exact problem, and I'm not sure what can be done to fix the problem. Ideally my kernel request listener could trigger before the onKernelException, so that it would properly set the locale beforehand, but currently it seems that the kernel request event is not triggered during a 404. I took a look at http://symfony.com/doc/current/components/http_kernel/introduction.html to better understand Symfony's request sequence, but I'm not really clear on the sequence that happens in a bad request, but it looks like in the case of an exception, it skips most of the request flow and goes straight to the response, and as I recall from http://symfony.com/doc/current/book/translation.html#handling-the-user-s-locale
"Setting the locale using $request->setLocale() in the controller is too late to affect the translator. Either set the locale via a listener (like above), the URL (see next) or call setLocale() directly on the translator service."
Is there a way to use the trans filter on a twig templated 404 page?
Try to inject the #translator and use its method setLocale.
['welcome_url' => $this->router->generate("welcome")]
And why did you create link in the listener? You should do it in the template using twig function called path.

Extjs 4 - Retrieve data in json format and load a Store. It sends OPTION request

I'm developing an app with Spring MVC and the view in extjs 4. At this point, i have to create a Grid which shows a list of users.
In my Spring MVC controller i have a Get method which returns the list of users in a jsonformat with "items" as a root.
#RequestMapping(method=RequestMethod.GET, value="/getUsers")
public #ResponseBody Users getUsersInJSON(){
Users users = new Users();
users.setItems(userService.getUsers());
return users;
}
If i try to access it with the browser i can see the jsondata correctly.
{"items":[{"username":"name1",".....
But my problem is relative to request of the Ext.data.Store
My Script is the following:
Ext.onReady(function(){
Ext.define('UsersList', {
extend: 'Ext.data.Model',
fields: [
{name:'username', type:'string'},
{name:'firstname', type:'string'}
]
});
var store = Ext.create('Ext.data.Store', {
storeId: 'users',
model: 'UsersList',
autoLoad: 'true',
proxy: {
type: 'ajax',
url : 'http://localhost:8080/MyApp/getUsers.html',
reader: {type: 'json', root: 'items'}
}
});
Ext.create('Ext.grid.Panel',{
store :store,
id : 'user',
title: 'Users',
columns : [
{header : 'Username', dataIndex : 'username'},
{header : 'Firstname', dataIndex: 'firstname'}
],
height :300,
width: 400,
renderTo:'center'
});
});
When the store tries to retrieve the data and launchs the http request, in my firebug console appears OPTIONS getUsers.html while the request in the browser launchs GET getUsers.html
As a result, Ext.data.Store has not elements and the grid appears with the columnames but without data. Maybe i've missed something
Thank you
You can change the HTTP methods that are used by the proxy for the different CRUD operations using actionMethods.
But, as you can see in the doc (and as should obviously be the case), GET is the default for read operations. So the OPTIONS request you are observing is quite puzzling. Are you sure that there's not another part of your code that overrides the default application-wide? Maybe do a search for 'OPTIONS' in all your project's JS files, to try and find a possible suspect. Apparently there's no match in the whole Ext code, so that probably doesn't come from the framework.
Edit:
Ok, I think I've got it. If your page is not accessed from the same domain (i.e. localhost:8080, the port is taken into account), the XHR object seems to resort to an OPTIONS request.
So, to fix your problem, either omit the domain name completely, using:
url: '/MyApp/getUsers.html'
Or double check that your using the same domain and port to access the page and make the requests.

Resources