Guzzle – no request in Symfony accessing Parse.com API - symfony

I would like to use Guzzle to create request.
My settings looks like this:
$request = $client->createRequest('GET', 'https://api.parse.com/1/classes/class');
$request->setHeader('Content-Type', 'application/json');
$request->setHeader('X-Parse-Application-Id', 'id');
$request->setHeader('X-Parse-REST-API-Key', 'key');
$response = $client->send($request);
And always, I get
Client error response
[status code] 401
[reason phrase] Unauthorized
[url] https://api.parse.com/1/classes/class
I'm sure I have correct ID and KEY. Also, there is no API call in debug toolbar.

when i access the url it prompts me with basic auth
so i think you have to do sth like
$request->setAuth($user, $pass);
before sending

Related

python fastapi redirect and authenticate

I'm trying to authenticate the user after visiting the registration link
(link example: http://127.0.0.1:8000/confirm-email?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9F)
My code:
#app.get("/confirm-email", status_code=200, )
def confirm_email(
token: str = fastapi.Query(..., min_length=64, max_length=256,
db: Session = fastapi.Depends(database.get_db)):
if user := crud.read_user_by(db, column='current_token', value=token):
if user.created_datetime + timedelta(minutes=30) > datetime.now(): # TODO change minutes to days
return fastapi.responses.RedirectResponse(
url="http://127.0.0.1:8000/users/me",
headers={"access_token": token, "token_type": "bearer"})
else:
raise fastapi.HTTPException(
status_code=fastapi.status.HTTP_410_GONE,
detail="Confirmation link is expired")
else:
raise fastapi.HTTPException(
status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
detail="Wrong token")
#app.get("/users/me")
def read_users_me(token: str = fastapi.Depends(oauth2_scheme),
db: Session = fastapi.Depends(database.get_db)):
try:
return services.get_user_by_token(db=db, token=token)
except Exception as e:
raise fastapi.HTTPException(
status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
But every time I'm failing when trying to use /users/me endpoint (getting 401 error, UNAUTHORIZED).
Maybe I put the token in the wrong place or using wrong headers?
If using OAuth 2.0 and wanting to set the access_token in a request, tipically, it goes into the Authorization header like the example in the RFC: Authorization: Bearer mF_9.B5f-4.1JqM - in the example, mF_9.B5f-4.1JqM would be the value of the token.
It seems to me that you are accessing the users/me endpoint with the headers access_token: [token value] and token_type: "bearer". Instead, I believe the following header should be set: Authorization: Bearer [token value]
After a little researching, I figured out that redirection by specification can't have authorization headers (browser/client will just ignore it mainly). So even if headers are correct - it's nonsense. One possible solution to use URL.

Angular2 post with mailchimp

My post works in postman but doesn't work inside my app. What am I doing wrong?
let data = obj;
let url = 'https://us123.api.mailchimp.com/3.0/lists/{somenumber}/members';
let username: string = 'user';
let password: string = 'mytokenhere';
let headers = new Headers();
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Content-Type", "application/x-www-form-urlencoded");
return this._http.post(url, data, {headers: headers}).subscribe(
data => this.response(data),
error => this.response(error)
);
I'm getting a CORS error in app:
'XMLHttpRequest cannot load https://us123.api.mailchimp.com/3.0/lists/{{somenumber}}/members. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 501.'
Mailchimp doesn't support client side calls to their API. What you would need to do is setup a server that can proxy the requests from the browser to Mailchimp. There isn't much you can do client side to get it to work if the Mailchimp API doesn't provide the CORS response headers.
If your API that you create is on the same domain as the website, then the CORS issue would be eliminated (or you can also fix by setting the appropriate headers)
See the note under Authentication:
https://developer.mailchimp.com/documentation/mailchimp/guides/get-started-with-mailchimp-api-3/
More Info:
https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/

bad http authentication header format auth0 asp.net

I am using auth0 with ASP.NET for roles and permission implementation. I want to fetch all users details by using auth0 api. Below is my code,
Code 1:
var apiClient = new ManagementApiClient("Bearer <<Token>>", new Uri("<<URL>>"));
var allClients = await apiClient.Clients.GetAllAsync();
Code 2:
var client = new ManagementApiClient("Authorization: Bearer <<Token>>", new Uri("<<URL>>"));
IPagedList<User> users = await client.Users.GetAllAsync();
Above both code giving me error:
"bad http authentication header format auth0 asp.net"
tried same token and url in postman, And it's returning result,
Where I need to change to make it work?
According to the usage documentation for the ManagementApiClient class, the constructor receives just the token, so you should be calling it like:
new ManagementApiClient("<<Token>>", new Uri("<<URL>>"));
It will then automatically include that token in an HTTP Authorization header using the Bearer scheme.

Symfony2 + FosOauth: token get, but requests are anonymous

I have installed and configurated FosOauthBundle but I have this problem: I can get Token And Refresh token with this line of code:
$ http POST http://localhost:8888/app_dev.php/oauth/v2/token grant_type=password client_id=1_3bcbxd9e24g0gk4swg0kwgcwg4o8k8g4g888kwc44gcc0gwwk4 client_secret=4ok2x70rlfokc8g0wws8c8kwcokw80k44sg48goc0ok4w0so0k username=MYEMAIL password=MYPASS
If I pass a wrong MYEMAIL or a wrong MYPASS symfony reply me with an error (and this is correct). Users are manged via FosUserBundle.
Now, How can I use token to say symfony that I'm a registered user ?
I have created this "api" in my controller:
public function getDemosAction()
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$view = $this->view($user);
return $this->handleView($view);
}
and I call it via this code:
$curl -H "Authorization: Bearer NGEwMGIxMzJkZmU5Yjc3YmM2ZjViNmE0YWFhYTEwOTg1MjI5NzIyNDkwNmFhYTUzMTRkZTk3MzEyNjA4OWY0Ng" http://localhost:8888/app_dev.php/api/demos
but it return me ALWAYS "anon.".
Where is my error ?
The problem was the order of firewall directives in security.yml. I have found the solution via this other question: Symfony2 OAuth keeps giving me a login page when a token is provided

guzzle php http client cookies setup

I am trying to migrate from Zend Http Client to Guzzle Http Client. I find Guzzle well featured and easy to use for the most part, But I think it is not well documented when it comes to using Cookie plugin. So my question is how do you set cookies for the HTTP request you are going to make against the server, in Guzzle.
Using Zend Client you would do something as simple as :
$client = new HttpClient($url); // Zend\Http\Client http client object instantiation
$cookies = $request->cookies->all(); // $request Symfony request object that gets all the cookies, as array name-value pairs, that are set on the end client (browser)
$client->setCookies($cookies); // we use the above client side cookies to set them on the HttpClient object and,
$client->send(); //finally make request to the server at $url that receives the cookie data
So, how do you do this in Guzzle. I have looked at http://guzzlephp.org/guide/plugins.html#cookie-session-plugin. But I felt it is not straightforward and couldn't get my head around it. May be someone can help ??
This code should achieve what is asked for, i.e to set the cookies on the request before making guzzle client request
$cookieJar = new ArrayCookieJar(); // new jar instance
$cookies = $request->cookies->all(); // get cookies from symfony symfony Request instance
foreach($cookies as $name=>$value) { //create cookie object and add to jar
$cookieJar->add(new Cookie(array('name'=>$name, 'value'=>$value)));
}
$client = new HttpClient("http://yourhosturl");
$cookiePlugin = new CookiePlugin($cookieJar);
// Add the cookie plugin to the client object
$client->addSubscriber($cookiePlugin);
$gRequest = $client->get('/your/path');
$gResponse = $gRequest->send(); // finally, send the client request
When the response comes back from the server with set-cookie headers you have those cookies available in the $cookieJar.
Cookie jar can also be gotten from the CookiePlugin method
$cookiePlugin->getCookieJar();
Or without cookie plugin
$client = new HttpClient();
$request = $client->get($url);
foreach($cookies as $name => $value) {
$request->addCookie($name, $value);
}
$response = $request->send();

Resources