I use this library : Oauth2 PHP
I can't find the setting to change the expiration time, I tried:
new OAuth2\Server($this->_mem, array('use_jwt_access_tokens' => true, 'access_token_lifetime' => 2419200));
But the lifetime of the token is always 3600. What's the right setting?
Edit: As suggested, I tried to use refresh token
new OAuth2\Server($this->_mem, array('use_jwt_access_tokens' => true, 'always_issue_new_refresh_token' => true));
The client_credential grant type + JWT bearer works but I never get a refresh token (only access token). Even upon token verification, I never get a refresh token.
Edit: Since the refresh doesn't work for me, as suggested I tried to set the token expiration time doing
new OAuth2\Server($this->_mem, array('use_jwt_access_tokens' => true, 'access_lifetime' => 12000));
The response upon client credential still returns a short token
{ ["access_token"]=> string(648) "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpZCI6ImU0NjE0MzdhMjY2YjFkNWY0OWU5MDY5MjQwODg5NjU0MDI2ZGRmODAiLCJpc3MiOiIiLCJhdWQiOiI4OWM2MjRmNTNiYTVmOTM3NjFmZWFhNmU1MGI1ZDk1NGQ4ZGRjMTIxIiwic3ViIjpudWxsLCJleHAiOjE0MzQ0NjI2NDIsImlhdCI6MTQzNDQ1OTA0MiwidG9rZW5fdHlwZSI6ImJlYXJlciIsInNjb3BlIjoicHVibGljIHJlYWRfbmV3cyJ9.Mk_KyUk_8yPnq9eEjvgVOJXBOkQSifAPbEaUvY4X9WvfmImPnC7PJx_99ODpiJR_gMLhZ3gBl1gQEJ2z6xUZ83dntCYzGWumkVLNpJG8omuVkmZqNnbLYYXl-vzmGOblceeDrKw_lrXc4rb72BeFaMeZWwFV7YMrgA0LOsYyZmAiDblcbHtpPGpUd2EC3y7VxLnyA8u07eY4aswOHwClPlDwHX_HwfMUmDLWkoTcrRf1AvKn-cnj41eL0SU9AJHWab8AOK7lxDsaqnits5pXj--cG9hr8pWOsFPQ2D9qYOsMvbEOi4zDJEdaIp-qvzn6N5Wrm5GxdbU1AqwvM531hQ" ["expires_in"]=> int(3600) ["token_type"]=> string(6) "bearer" ["scope"]=> string(16) "public" }
It appears it was a cache issue, the token is now set to the proper expiration length/time
You can change the access_token lifetime using the access_lifetime OAuth2\Server config parameter from examining the code.
The access_lifetime config parameter is used in creating the token in OAuth2\ResponseType\JwtAccessToken line 63:
$expires = time() + $this->config['access_lifetime'];
This can be set when instantiating the server which takes the following config parameters as listed in OAuth2\Server lines 109 - 126.
// merge all config values. These get passed to our controller objects
$this->config = array_merge(array(
'use_jwt_access_tokens' => false,
'store_encrypted_token_string' => true,
'use_openid_connect' => false,
'id_lifetime' => 3600,
'access_lifetime' => 3600,
'www_realm' => 'Service',
'token_param_name' => 'access_token',
'token_bearer_header_name' => 'Bearer',
'enforce_state' => true,
'require_exact_redirect_uri' => true,
'allow_implicit' => false,
'allow_credentials_in_request_body' => true,
'allow_public_clients' => true,
'always_issue_new_refresh_token' => false,
'unset_refresh_token_after_use' => true,
), $config);
There is also support for refresh tokens according to the code for Server.php and JwtAccessToken.php.
In server.php (where you are passing grant type and client credentials)
$config = array(
'access_lifetime' => 86400
);
$server = new OAuth2\Server($storage, $config);
source: https://github.com/bshaffer/oauth2-server-php/issues/699
Related
In my tests, I "mock" my OAuth process as follows:
$oauthMiddleware = new OAuth2Middleware(new NullGrantType);
$oauthMiddleware->setAccessToken([
"access_token" => "290473f650...",
"expires_in" => 3600,
"token_type" => "Bearer",
"scope" => "*"
]);
$handlerStack = HandlerStack::create();
$handlerStack->push($oauthMiddleware);
$client = new GuzzleHttpClient([
'handler' => $handlerStack,
RequestOptions::AUTH => 'oauth',
]);
I follow the instructions given in the repository:
use kamermans\OAuth2\GrantType\NullGrantType;
$oauth = new OAuth2Middleware(new NullGrantType);
$oauth->setAccessToken([
// Your access token goes here
'access_token' => 'abcdefghijklmnop',
// You can specify 'expires_in` as well, but it doesn't make much sense in this scenario
// You can also specify 'scope' => 'list of scopes'
]);
But instead of using the manually set access token, it throws:
No access token is present, and there is no way to obtain one with NullGrantType.
I traced the exception back to kamermans\OAuth2\GrantType\NullGrantType::getRawData(). In the documentation, it says, for the exception not to be thrown, setAccessToken() must be called. But as you can see in my code, I do exactly that (correct me if I'm wrong). Does anyone see what I'm doing wrong?
Basically, I am trying to connect to a SOAP service with 2 way SSL (HTTP client certificate authentication).
I am using PHP SoapClient for this within Laravel.
This is what I have, and it allows me to connect and returns the expected response. So the method is basically correct and the certificate is fine etc. It's just I am having trouble with what I guess is the 2 way SSL part.
$client = new \SoapClient('localwsdlfile.wsdl', array(
'local_cert' => 'localcert.pem',
'passphrase' => 'passphrase',
// 'location' => 'https://wsmurl/login/' // Uncomment to login
));
$response = $client->Get(array(
"AccessKey" => "accesskey",
"ProductID" => "SOMEPRODUCT",
"Scope" => "SOMESCOPE",
"Parameters" => array('Param' => array('_' => 'DATATOLOOKUP', 'id'=>'MOREDATATOLOOKUP'))
));
print_r($response);
The only problem is (obviously because I'm doing something wrong), is I need to add the line 'location' => 'https://wsmurl/login/' the first time I try to connect, otherwise I get an error "SoapFault Login Required"
I then remove the line 'location' => 'https://wsmurl/login/', otherwise, I get an error "SoapFault looks like we got no XML document".
The service provider has a 600 second timeout, where I don't have to "login" again for upto 600 seconds.
After removing this line 'location' => 'https://wsmurl/login/', then it works as expected. Obviously, I can't manually add and remove this line, and I guess I am not doing this correctly.
Can someone tell me a better way to do this please?
Thanks,
Because the location for the login and localwsdlfile.wsdl is different, I could not do it with one call. So we created a function using curl to login and if login is successful it will proceed to the soapclient. Thanks to Brian from freelancer for his assistance here.
$client = new SoapClient('wsdl/VocusSchemas/localwsdlfile.wsdl', array(
'trace' => 1,
'exception' => true
));
try {
$response = $client->Get(array(
// "AccessKey" => "MADAITABNSAATOT1",
"AccessKey" => "accesskey",
"ProductID" => "SOMEPRODUCT",
"Scope" => "SOMESCOPE",
"Parameters" => array('Param' => array('_' => 'DATATOLOOKUP', 'id' => 'MOREDATATOLOOKUP'))
));
I am using laravel with the thujohn/twitter package.
But i want whenever any use registered they will provide us CONSUMER_KEY and CONSUMER_SECRET and we will use that details to post the tweet,favorites tweet etc.
But in the thujohn/twitter package the CONSUMER_KEY and CONSUMER_SECRET is set one time and that will use for all users and i want to use each register user will use their own consumer details.
Any one know any solution on the same
Looking at the source code you have the reconfigure method:
/**
* Set new config values for the OAuth class like different tokens.
*
* #param Array $config An array containing the values that should be overwritten.
*
* #return void
*/
public function reconfig($config)
{
// The consumer key and secret must always be included when reconfiguring
$config = array_merge($this->parent_config, $config);
parent::reconfigure($config);
return $this;
}
So you can pass an array with the configs you want:
Twitter::reconfigure([
'consumer_key' => '',
'consumer_secret' => '',
'token' => '',
'secret' => '',
]);
This configs will then be passed to the parent which is another library called tmhOAuth here's the code for that:
public function reconfigure($config=array()) {
// default configuration options
$this->config = array_merge(
array(
// leave 'user_agent' blank for default, otherwise set this to
// something that clearly identifies your app
'user_agent' => '',
'host' => 'api.twitter.com',
'method' => 'GET',
'consumer_key' => '',
'consumer_secret' => '',
'token' => '',
'secret' => '',
// OAuth2 bearer token. This should already be URL encoded
'bearer' => '',
// oauth signing variables that are not dynamic
'oauth_version' => '1.0',
'oauth_signature_method' => 'HMAC-SHA1',
// you probably don't want to change any of these curl values
'curl_http_version' => CURL_HTTP_VERSION_1_1,
'curl_connecttimeout' => 30,
'curl_timeout' => 10,
// for security this should always be set to 2.
'curl_ssl_verifyhost' => 2,
// for security this should always be set to true.
'curl_ssl_verifypeer' => true,
// for security this should always be set to true.
'use_ssl' => true,
// you can get the latest cacert.pem from here http://curl.haxx.se/ca/cacert.pem
// if you're getting HTTP 0 responses, check cacert.pem exists and is readable
// without it curl won't be able to create an SSL connection
'curl_cainfo' => __DIR__ . DIRECTORY_SEPARATOR . 'cacert.pem',
'curl_capath' => __DIR__,
// in some cases (very very odd ones) the SSL version must be set manually.
// unless you know why your are changing this, you should leave it as false
// to allow PHP to determine the value for this setting itself.
'curl_sslversion' => false,
'curl_followlocation' => false, // whether to follow redirects or not
// support for proxy servers
'curl_proxy' => false, // really you don't want to use this if you are using streaming
'curl_proxyuserpwd' => false, // format username:password for proxy, if required
'curl_encoding' => '', // leave blank for all supported formats, else use gzip, deflate, identity etc
// streaming API configuration
'is_streaming' => false,
'streaming_eol' => "\r\n",
'streaming_metrics_interval' => 10,
// header or querystring. You should always use header!
// this is just to help me debug other developers implementations
'as_header' => true,
'force_nonce' => false, // used for checking signatures. leave as false for auto
'force_timestamp' => false, // used for checking signatures. leave as false for auto
),
$config
);
}
I'm trying to make a post request to the same subdomain with GuzzleHttp in a Laravel 5.1 installation, but as a response the login page is returned, showing that a new Session has been created in the request. The current session is not affected.
Why does Laravel create a new session?
In session.php I have the following values:
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 120,
'expire_on_close' => true,
'files' => storage_path('framework/sessions'),
'cookie' => 'admin_mydomain_com_session',
'path' => '/',
'domain' => 'admin.mydomain.com',
'secure' => false
In my controller I use the following code to make the request:
// Create headers
$headers = array(
'X-CSRF-Token' => csrf_token()
);
// Create data
$data = array(
'param' => 'param',
'_token' => csrf_token()
);
// Create a POST request
$client = new Client();
$res = $client->request('POST', 'http://admin.mydomain.com/my-url',
array(
'headers' => $headers,
'form_params' => $data
)
);
$statusCode = $res->getStatusCode();
$body = $res->getBody();
echo $body; // Shows me the login page
The answer is really to understand how sessions work. When you make a request via a browser lets say, the response issued by the server will include a cookie with a session id. That id is what identifies you to the server. When you navigate a site through your browser the request it issues includes the cookies.
So when your creating a request via Guzzle your leaving out the cookie from the previous response. Hence the server will always create a new session id for you.
I'm working on a web app using Slim, but I'm facing an issue with setting and persisting sessions.
Here is my index.php. I am trying to set a csrfToken key in the $_SESSION array, so that every request that is made through the app checks if the user has a csrfToken key, if not it will create one.
I'm just confused as to why it isn't persisting because on the next request it's gone. session_start is being called, it's being called automatically by '\Slim\Middleware\SessionCookie'.
Any ideas why this wouldn't be working? And would it be better to place this into middleware or use a hook?
use duncan3dc\Laravel\Blade;
use duncan3dc\Helpers\Env;
# TODO: Bootstrap the app. Move this to a seperate file. Dev only.
R::setup('mysql:host=localhost;dbname=somedb','user','pass');
$app = new \Slim\Slim(array(
'mode' => 'development',
'templates.path' => './views',
'cookies.encrypt' => true,
'cookies.secret_key' => 'mylongsecretkey',
'cookies.cipher' => MCRYPT_RIJNDAEL_256,
'cookies.cipher_mode' => MCRYPT_MODE_CBC
));
$app->add(new \Slim\Middleware\SessionCookie(array(
'expires' => '10 minutes',
'path' => '/',
'domain' => 'site.com',
'secure' => false, # Contact client to discuss using SSL
'httponly' => false,
'name' => '_sus',
'secret' => 'mylongsecretkey', # Do I need this twice?
'cipher' => MCRYPT_RIJNDAEL_256,
'cipher_mode' => MCRYPT_MODE_CBC
)));
# Not persisting ...
if(!isset($_SESSION['csrfToken']))
$_SESSION['csrfToken'] = hash("sha512",mt_rand(0,mt_getrandmax()));
# TODO: Bootstrap these.
require 'routes/index.php';
require 'routes/dashboard.php';
require 'routes/signup.php';
require 'routes/contactus.php';
require 'routes/privacypolicy.php';
require 'routes/testimonials.php';
require 'routes/login.php';
$app->run();
I figured out how to do it after reading more into hooks.
$app->hook('slim.before.router', function() use ($app){
if(!isset($_SESSION['csrfToken']))
$_SESSION['csrfToken'] = hash("sha512",mt_rand(0,mt_getrandmax()));
});