-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Library packed with Codeigniter #72
Comments
I type in terminal: curl http://authorizeserver.local/oauth2 -d 'client_id=test&grant_type=authorization_code&client_details=test&redirect_uri=http://test&response_type=code' and I get this: |
And what happens if you do: curl http://authorizeserver.local/oauth2?client_id=test&grant_type=authorization_code&client_details=test&redirect_uri=http://test&response_type=code ? |
I got this: [2] 19205 |
It's works! |
[Fix] implement for Codeigniter Framework <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
*
*/
class Oauth2 extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper(array('url', 'form'));
// Initiate the request handler which deals with $_GET, $_POST, etc
$request = new League\OAuth2\Server\Util\Request();
// Initiate a new database connection
$db = new League\OAuth2\Server\Storage\PDO\Db('mysql://root:root@localhost/alex_oauth');
// Create the auth server, the three parameters passed are references
// to the storage models
$this->authserver = new League\OAuth2\Server\Authorization(
new League\OAuth2\Server\Storage\PDO\Client($db),
new League\OAuth2\Server\Storage\PDO\Session($db),
new League\OAuth2\Server\Storage\PDO\Scope($db)
);
// Enable the authorization code grant type
$this->authserver->addGrantType(new League\OAuth2\Server\Grant\AuthCode($this->authserver));
}
public function index()
{
try {
// Tell the auth server to check the required parameters are in the
// query string
$params = $this->authserver->getGrantType('authorization_code')->checkAuthoriseParams();
$this->session->set_userdata('client_id', $params['client_id']);
$this->session->set_userdata('client_details', $params['client_details']);
$this->session->set_userdata('redirect_uri', $params['redirect_uri']);
$this->session->set_userdata('response_type', $params['response_type']);
$this->session->set_userdata('scopes', $params['scopes']);
// Redirect the user to the sign-in route
redirect('/oauth2/signin');
} catch (Oauth2\Exception\ClientException $e) {
echo $e->getMessage();
// Throw an error here which says what the problem is with the
// auth params
} catch (Exception $e) {
echo $e->getMessage();
// Throw an error here which has caught a non-library specific error
}
}
public function signin()
{
// Retrieve the auth params from the user's session
$params['client_id'] = $this->session->userdata('client_id');
$params['client_details'] = $this->session->userdata('client_details');
$params['redirect_uri'] = $this->session->userdata('redirect_uri');
$params['response_type'] = $this->session->userdata('response_type');
$params['scopes'] = $this->session->userdata('scopes');
// Check that the auth params are all present
foreach ($params as $key=>$value) {
if ($value == null) {
// Throw an error because an auth param is missing - don't
// continue any further
// echo "stop";
// exit;
}
}
// Process the sign-in form submission
if ($this->input->post('signin') != null) {
try {
// Get username
$u = $this->input->post('username');
if ($u == null || trim($u) == '') {
throw new Exception('please enter your username.');
}
// Get password
$p = $this->input->post('password');
if ($p == null || trim($p) == '') {
throw new Exception('please enter your password.');
}
// Verify the user's username and password
// Set the user's ID to a session
if($u == 'f4hem' && $p == 'f4hem') {
$this->session->set_userdata('user_id', 'f4hem');
}
} catch (Exception $e) {
$params['error_message'] = $e->getMessage();
}
}
// Get the user's ID from their session
$params['user_id'] = $this->session->userdata('user_id');
// User is signed in
if ($params['user_id'] != null) {
// Redirect the user to /oauth/authorise route
redirect('/oauth2/authorize');
}
// User is not signed in, show the sign-in form
else {
echo form_open('/oauth2/signin');
echo form_label('Username', 'username');
echo form_input('username', '');
echo form_label('Password', 'password');
echo form_password('password', '');
echo form_submit('signin', 'Sign In!');
echo form_close();
}
}
public function authorize()
{
// init auto_approve for default value
$params['client_details']['auto_approve'] = 0;
// Retrieve the auth params from the user's session
$params['client_id'] = $this->session->userdata('client_id');
$params['client_details'] = $this->session->userdata('client_details');
$params['redirect_uri'] = $this->session->userdata('redirect_uri');
$params['response_type'] = $this->session->userdata('response_type');
$params['scopes'] = $this->session->userdata('scopes');
// Check that the auth params are all present
foreach ($params as $key=>$value) {
if ($value === null) {
// Throw an error because an auth param is missing - don't
// continue any further
// echo "stop";
// exit;
}
}
// Get the user ID
$params['user_id'] = $this->session->userdata('user_id');
// User is not signed in so redirect them to the sign-in route (/oauth/signin)
if ($params['user_id'] == null) {
redirect('/oauth2/signin');
}
// init autoApprove if in database, value is 0
$params['client_details']['auto_approve'] = isset($params['client_details']['auto_approve']) ? $params['client_details']['auto_approve'] : 0;
// Check if the client should be automatically approved
$autoApprove = ($params['client_details']['auto_approve'] == '1') ? true : false;
// Process the authorise request if the user's has clicked 'approve' or the client
if ($this->input->post('approve') == 'yes' || $autoApprove === true) {
// Generate an authorization code
$code = $this->authserver->getGrantType('authorization_code')->newAuthoriseRequest('user', $params['user_id'], $params);
// Redirect the user back to the client with an authorization code
$redirect_uri = League\OAuth2\Server\Util\RedirectUri::make(
$params['redirect_uri'],
array(
'code' => $code,
'state' => isset($params['state']) ? $params['state'] : ''
)
);
redirect($redirect_uri);
}
// If the user has denied the client so redirect them back without an authorization code
if($this->input->get('deny') != null) {
$redirect_uri = League\OAuth2\Server\Util\RedirectUri::make(
$params['redirect_uri'],
array(
'error' => 'access_denied',
'error_message' => $this->authserver->getExceptionMessage('access_denied'),
'state' => isset($params['state']) ? $params['state'] : ''
)
);
redirect($redirect_uri);
}
// The client shouldn't automatically be approved and the user hasn't yet
// approved it so show them a form
echo form_open('/oauth2/authorize');
echo form_submit('approve', 'yes');
echo form_close();
}
public function access_token()
{
try {
// Tell the auth server to issue an access token
$response = $this->authserver->issueAccessToken();
} catch (League\OAuth2\Server\Exception\ClientException $e) {
// Throw an exception because there was a problem with the client's request
$response = array(
'error' => $this->authserver->getExceptionType($e->getCode()),
'error_description' => $e->getMessage()
);
// Set the correct header
header($this->authserver->getExceptionHttpHeaders($this->authserver->getExceptionType($e->getCode())));
} catch (Exception $e) {
// Throw an error when a non-library specific exception has been thrown
$response = array(
'error' => 'undefined_error',
'error_description' => $e->getMessage()
);
}
header('Content-type: application/json');
echo json_encode($response);
}
} |
Step 1: http://authorizeserver.local/oauth2/?client_id=test&grant_type=authorization_code&client_details=test&redirect_uri=http://test.local&response_type=code **assuming was created client_id, redirect_uri, and client_secret in DB, exampel(client_id=test, redirect_uri=http://test.local/, client_secret=test) Step 2: http://authorizeserver.local/oauth2/signin **in this example, I use (username=f4hem, password=f4hem) Step 3: http://authorizeserver.local/oauth2/authorize and click button 'yes' Step 4: http://test.local/?code=WWrJy7Ww03fmZJwkvhLRPFF1ypsoOqegiKvy83AY&state= ** code was generated randomly by League Oauth2 Library Step 5: curl http://authorizeserver.local/oauth2/access_token -d "grant_type=authorization_code&client_id=test&redirect_uri=http://test.local&client_secret=test&code=WWrJy7Ww03fmZJwkvhLRPFF1ypsoOqegiKvy83AY" and Taraaaa.. you will get response token (generated randomly too by Library): {"access_token":"9P9dmgfxIAzjjMoWG8GvARita8dK1ZTN8lUtTR9i","token_type":"bearer","expires":1372105079,"expires_in":3600} Tq Alex.. |
Awesome.. can you please tell me how you get to load the library within this controller without using composer? |
No, I use composer too in this controller, my composer.json like this: {
"require": {
"league/oauth2-server": "2.*",
"zetacomponents/database": "1.4.6"
}
} and overload the composer bootstrap autoload generated by composer in bottom of file index.php codeigniter apps. the script like this: // Path to the vendor folder for Composer
define('VENDORPATH', FCPATH . 'vendor/');
/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------
*
* And away we go...
*
*/
// init Composer bootstrap
require_once VENDORPATH.'autoload.php';
// init Codeigniter bootstrap
require_once BASEPATH.'core/CodeIgniter.php'; |
thanks it's work :) |
how to intergrate this with ci? |
Please look in your frameworks documentation on how to integrate Composer packages. On 28 Jul 2013, at 10:54, nasaorc notifications@github.com wrote:
|
I followed the your step-by-step tutorial and i'm now stuck on this last process, in the access_token() action : $response = $this->authServer->issueAccessToken(); Is this issueAccessToken() by default no parameter? If so, when i check in Authorization (League\OAuth2\Server\Util\Request) there's this line: if (is_null($grantType)) { And the error response message is : {"error":"invalid_request","error_description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the "grant_type" parameter."} Your help is really much appreciated. |
You need to send |
Thanks for the reponse, but i did send it, tried via GET and POST: |
The request you're sending isn't even remotely valid.
On 12 Aug 2013, at 08:16, zeratool notifications@github.com wrote:
|
Yes, i followed those steps you mentioned, i am on the last part , the library already generated the code: code=RK2DjrHgp995U1wkaUhuJYoccddOCswoYGgSrBQW This code is saved in the table " oauth_session_authcodes" |
For additional information, the "client" is mobile app. |
It's ok now, thanks for your responses and for this cool library! |
Thank you so much. It works. Awsome library! |
Hi everyone. My doubt at this point is: How do I make requests to my API using the access_token that I got at Step 5 of this guide? I guess that what I need to know is what's the request syntax. The method that I want to reach with this request is: http://localhost/myapp/index.php/user/getUser Thank you so much. [SOLVED] This is what I was looking for: curl -H "Authorization: Bearer blMZK6gNQhxpjFKRUoK2gx45zQzN0Zw7WwAvjwca" http://localhost/myapp/index.php/controller/function_in_controller Everything works fine now. :) |
I have question alex, I have 3 controller in my authorizeserver based on CI.
Which GrantType should I set available in there controller, especially in /oauth2/token controller. |
Hello alex? Im getting "Fatal error: Call to undefined method DB::query() in F:\Work\xampp\htdocs\oauth\application\controllers\model_session.php on line 79" when i enter username and password then press the yes button. This is my db.php conn = new PDO('mysql:host=localhost;dbname=oauth2', '***', ''); } public function query($sql = '', $params = array()) { $statement = $this->conn->prepare($sql); $statement->setFetchMode(PDO::FETCH_OBJ); $statement->execute($params); return $statement; } public function getInsertId() { return (int) $this->conn->lastInsertId(); } ``` } |
Could somebody please provide a sample project for this? Finding it hard to get my head around everything. |
Ignore my last comment. After about 12 hours of messing around with this I've finally got a working implementation. One problem I noticed though.... When requesting an access token with an invalid code, a PHP error is thrown and outputted: curl http://localhost2/oauth2/oauth2/access_token -d "grant_type=authorization_code&client_id=test&redirect_uri=http://test.local&client_secret=test&code=LgkxoxFLXRozfJ9olQ18a2d4ybm3MTgLI5bEGEF6"
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>A PHP Error was encountered</h4>
<p>Severity: Warning</p>
<p>Message: header() expects parameter 1 to be string, array given</p>
<p>Filename: controllers/oauth2.php</p>
<p>Line Number: 220</p>
</div>{"error":"invalid_grant","error_description":"The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client. Check the \"code\" parameter."} I resolved this issue by removing line 220 from the controller, like so. It doesn't seem to do much anyway: // Set the correct header
//header($this->authserver->getExceptionHttpHeaders($this->authserver->getExceptionType($e->getCode()))); |
I have imported library in my codeigniter project using composer in application folder
Also I have changed composer_autoload to TRUE in config file.
But when I try to create instance of classess. It gives me error class "ClientRepository" not found.
Please assist me! |
@vivek-1874596 You need to implement the repository interfaces - http://oauth2.thephpleague.com/installation/ |
Hi @fahmiardi,
I copied the "Oauth2" classes from this issue and there seemed to be missing some packages and classes:
Can you advise where I can download the missing packages/classes? |
@nimsothea - Try to download using composer, It will download all required classes. Follow steps added by @fahmiardi - #72 (comment) It will definitely help you. |
Yep, I was using as well (composer require league/oauth2-server "^7.1") |
@nimsothea I don't think you have downloaded version 7.1.1 or you have some customisations as some of the files you are trying to get aren't provided by this package such as You should check your version in your composer file. Hope this helps |
this is code Ouath2 Controller. I already include "zetacomponents/database": "1.4.6" in composer.json
The text was updated successfully, but these errors were encountered: