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
Related
I would like your opinion in order to achieve something. I have an api and I want to restrictionate the access of the user. But short story long, in action login controller of page /login I generate the token for the user autheticated and I return it. Well, here comes one of my question/problem. It's mandatory in a action controller to return a response, and my token it's send in json format and it's displayed on browser, but I don't want this, I just want to keep in response or in something so that my angular part to take that token and to take care of it in its way. So my method login:
public function loginAction(Request $request)
{
$username= $this->get('security.token_storage')->getToken()->getUser()->getEmail();
$serviceUser = $this->container->get('ubb_user_login');
$tokenUser = $serviceUser->generateToken($username);
$response = new JsonResponse(array('Token' => $tokenUser));
return $response;
}
2nd problem. I do not know in angular where to extract the token. In a controller I tried something:
app.controller('loginApi', function ($scope, $http, $window){
$http.get(
'/api/user/login'
).then(function (success) {
$scope.token = success.data.Token;
$window.localStorage.setItem('Token', token); // it's okay used like this localStorage?
});
});
Here, I want only to take the token from /login action, to save it in local storage, and then to display it on every request using $http request interceptor. That part works. If I send a random string in header auth it's working and it gives me access to api:
function httpInterceptor() {
return {
request: function(config) {
config.headers.authorization = 'jdjdnnkdkd';
return config;
},
responseError: function(errorResponse) {
switch (errorResponse.status) {
case 403:
window.location = '/login';
break;
case 401:
window.location = '/login';
}
return $q.reject(errorResponse);
}
}
}
So, the problems I encounter:
1) How to send the token in order for angular to take it, but to not be displayed in the browser? Let's say that I have a menu that access the api, and if the user it's not authenticated,clicking on a link unauthenticated it's sending me on the login page, and after I auth with success, to redirect me on the menu?
2) After returning the token, where exactly to use it in angular? In which controller? And how to save it?
Much appreciation, thank you.
It seems like you need a separate api resource for working with the tokens. Have you tried using FOSOAuthServeBundle? It helps a lot with setting up oauth authentication, tokens etc.
In general you need to have a separate call for the token, i.e.:
angluar app makes request to a get token resource, a token is returned and temporarily stored in the angular app
use that token for each subsequent request - check the oauth bundle config on how to set which urls have to be oauth protected, but that bundle takes care of this for you
Regarding your angular issue, look at this q/a How to store authentication bearer token in browser cookie using AngularJS
I'm trying to create calendar event via PHP for one particular user - say developement#example.com.
I've created Service Account in Google Developers Console, got ClientID, E-mail address and private key. The authentication is done with code:
$client = new Google_Client();
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$cred = new Google_Auth_AssertionCredentials(
'somelongstring#developer.gserviceaccount.com.',
array('https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.readonly'),
file_get_contents('p12 file'));
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
This type of authentication seems pretty OK. But all events are created as user with E-mail address somelongstring#developer.gserviceaccount.com instead of developement#example.com.
I've tried setting sub parameter:
$cred = new Google_Auth_AssertionCredentials(
....
$cred->sub = 'developement#example.com';
$client->setAssertionCredentials($cred);
But this piece of code throws exception:
Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{ "error" : "access_denied", "error_description" : "Requested client not authorized." }'
And now I'm lost. Any advice?
OK, resolved ;-)
Problem was with developement on own domain.
As mentioned in other question and in Google SDK Guide I have to grant access for service account to all scopes I request access. I forgot to add read-only scope.
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
I'm working with google analytics apis v3 to receive traffic data, the language in use is php, the problem is that until a few days ago I obtained the data, now I have this error:
(401) Login Required
I logged on:
gmail.com
analytics.google.it
on the console of google is all enabled properly, because a few days ago it worked ..
here:
http://ga-dev-tools.appspot.com/explorer/
working properly ..
The authentication code is this:
require_once '/analytics/src/Google_Client.php';
require_once '/analytics/src/contrib/Google_AnalyticsService.php';
$client = new Google_Client();
$client->setAccessType('offline'); // default: offline
$client->setApplicationName('#########ca1');
$client->setClientId('#########99.apps.googleusercontent.com');
$client->setClientSecret('#########hs33t');
$client->setRedirectUri("#########/analytics/oauth2callback.php");
$client->setDeveloperKey('#########y86ePKOcHs'); // API key
# $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
}
The parameter $ _GET ['code'] is empty, and then the session token is not created.
Maybe it worked for a few days Just Because in the various tests of code That I did was logged.
you should pass the $_GET['code'] as a parameter to the $client->authenticate() method, like that
$client->authenticate($_GET['code']);
I have the folowing snippet of code to check use role however it returns me with a
The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL.
public function loginAction(){
$request = $this->getRequest();
$session = $request->getSession();
var_dump($this->get("security.context")->isGranted('ROLE_ADMIN'));
$response = new Response();
$response -> setContent("login facebook");
$response->send();
return array('name'=>'login facebook');
}
Why I am getting this error and how do I fix this ?
The exception message is pretty clear: One possible reason may be that there is no firewall configured for this URL. To check user role, you need a token which contains a user (anonymous or not). By default, if you don't configure a authentication provider for a given path, you won't get any security context.
The solution here is to add an authentication provider.