Code Monkey home page Code Monkey logo

oauth2-server's Introduction

PHP OAuth 2.0 Server

Latest Version Software License Build Status Coverage Status Quality Score Total Downloads

league/oauth2-server is a standards compliant implementation of an OAuth 2.0 authorization server written in PHP which makes working with OAuth 2.0 trivial. You can easily configure an OAuth 2.0 server to protect your API with access tokens, or allow clients to request new access tokens and refresh them.

Out of the box it supports the following grants:

  • Authorization code grant
  • Client credentials grant
  • Device authorization grant
  • Implicit grant
  • Refresh grant
  • Resource owner password credentials grant

The following RFCs are implemented:

This library was created by Alex Bilbie. Find him on Twitter at @alexbilbie.

Requirements

The latest version of this package supports the following versions of PHP:

  • PHP 8.1
  • PHP 8.2
  • PHP 8.3

The openssl and json extensions are also required.

All HTTP messages passed to the server should be PSR-7 compliant. This ensures interoperability with other packages and frameworks.

Installation

composer require league/oauth2-server

Documentation

The library documentation can be found at https://oauth2.thephpleague.com. You can contribute to the documentation in the gh-pages branch.

Testing

The library uses PHPUnit for unit tests.

vendor/bin/phpunit

Continuous Integration

We use Github Actions, Scrutinizer, and StyleCI for continuous integration. Check out our configuration files if you'd like to know more.

Community Integrations

Changelog

See the project changelog

Contributing

Contributions are always welcome. Please see CONTRIBUTING.md and CODE_OF_CONDUCT.md for details.

Support

Bugs and feature request are tracked on GitHub.

If you have any questions about OAuth please open a ticket here; please don't email the address below.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

This package is released under the MIT License. See the bundled LICENSE file for details.

Credits

This code is principally developed and maintained by Andy Millington.

Between 2012 and 2017 this library was developed and maintained by Alex Bilbie.

PHP OAuth 2.0 Server is one of many packages provided by The PHP League. To find out more, please visit our website.

Special thanks to all of these awesome contributors.

Additional thanks go to the Mozilla Secure Open Source Fund for funding a security audit of this library.

The initial code was developed as part of the Linkey project which was funded by JISC under the Access and Identity Management programme.

oauth2-server's People

Contributors

alexbilbie avatar apollopy avatar carusogabriel avatar ceeram avatar cziegenberg avatar dhrrgn avatar erickjth avatar eugene-borovov avatar filecage avatar fizzka avatar frankdejonge avatar frederikbosch avatar grahamcampbell avatar hywan avatar iansltx avatar janhopman-nhb avatar jc5 avatar juliangut avatar lookyman avatar lucadegasperi avatar lucasantarella avatar marc-mabe avatar michaelgooden avatar michaelhogg avatar michalbundyra avatar sephster avatar ssigwart avatar toopay avatar uphlewis avatar vinkla avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

oauth2-server's Issues

Dynamic Configuration of redirect_uri

Per the OAuth 2.0 spec section 3.2.1.3 on page 13 (emphasis added):

When a redirection URI is included in an authorization request, the authorization server
MUST compare and match the value received against at least one of the registered
redirection URIs (or URI components) as defined in section 6...

The way the storage currently works is that it is checking for an exact match of the redirect_uri. This fails when say your provider is attempting to append a query string to the redirect_uri.

I'm currently working on a fix for this internally for myself...but wanted to make sure I'm seeing this correctly and am not just overlooking something. Thoughts?

OAuth 2.0 authorization server tutorial - Session

Hi,

First of all do I want to thank you for this framework.

After fixing some other little bugs in the example I run into another one.
I dont know if its my own fault or that the example is missing some line of code but
In al the functions except for the constructor the Session class can not be found.

in example:
$params['client_id'] = Session::get('client_id');
$params['client_details'] = Session::get('client_details');
$params['redirect_uri'] = Session::get('redirect_uri');
$params['response_type'] = Session::get('response_type');
$params['scopes'] = Session::get('scopes');

of course this also applies to the 'Session::put()'

Can someone please clarify why / How I can fix this.

Thanks in advance.

Conditional Flag for checking for Access Token in header

Are there any plans in place to force the library to only check for an Authorization header by passing in a variable. Doing this would be useful in situations where an API would only look for Authorization header. By passing in this flag to the Resource->isValid() method (and therefore into the Resource->determineAccessToken() method - the developer in this case is choosing to adopt the standards of the OAuth2 spec, whereby Authorization header is still supported, but the query param support is removed.

The official specification lays out how here - http://tools.ietf.org/html/rfc6749#section-7 - how it expects Authorization to take place when "Accessing Protected Resources" e.g. using our API. See bottom of paragraph two - how it expects the actual Access Token to be passed here http://tools.ietf.org/html/rfc6750#section-2

Integrating this with Codeigniter

You had a repo where you should how to do this and now that this has evolved, can you please provide some instructions on how to integrate this into Codeigniter?

Thanks,

getScopes relies on non-existent 'key' DB field

In src/League/OAuth2/Server/Resource.php line 197, getScopes calls for a 'key' column which isn't present in the SQL schema stored in sql/mysql.sql. I think it's supposed to be one of scope or name (or the schema file is wrong) but I don't know which so I haven't submitted a pull request.

Several problems in the 2.0 version

Hi,

great to see that the development is going one, because I didn't get any feedback on my suggestions regarding the database structure. I just updated my implementation an recognized the following problems:

General:

  1. Is it possible to move the PDO apdater into a sepparate project? I use another database layer and I would prefer to download only the neccessary components. Also this would allow to offer packages for other famous database layers like Zend DB.

Database:

  1. You renamed some fields in the oauth_client and oauth_scopes tables, which is problematic, because now some field names are reserved keyword in some DMBS (e.g. "key" in SqlServer). That's why I prefixed them...

  2. You renamed some id fields in the table, some not - e.g. 'client_id' in 'oauth_clients' to 'id', but 'endpoint_id' in 'oauth_client_endpoints' is still the same. It's okay to name it this way, but you should use the same naming convention for all tables.

  3. Renaming some of the proposed tables/fields is was a good idea, but the naming of the indexes and foreign keys doesn't match these new names now.

  4. Some fields have an empty default value, which doesn't make sense in most cases and would be treatet as NULL in some DBMS - this would lead to an error there, because NULL is not allowed for these fields.

  5. The new field "scope_ids" is missing in your SQL script. This information should be saved in a sepparate table, not in one field.

Session Interface:

  1. Why does the new method "removeAuthCode" delete the whole session and not just the auth code. One session can have more than one Auth Code, and all are deleted with this method.

  2. Why did you remove the client_id from "validateRefreshToken"? This is a security problem. Following the RFC, "The authorization server MUST maintain the binding between a refresh token and the client to whom it was issued." - this doesn't make sense, if this information is not checked in the validate method.

As soon as the problems are solved, I will try to provide the database structure for other DBMS.

Password Grant - allow multiple sessions per user

Firstly I wanted to thank you for your awesome library @alexbilbie :)

For the Password Grant, why are existing sessions deleted when the new session is created?

public function completeFlow($inputParams = null)
{
    ...
    // Delete any existing sessions just to be sure
    $this->authServer->getStorage('session')->deleteSession($authParams['client_id'], 'user', $userId);

    // Create a new session
    $sessionId = $this->authServer->getStorage('session')->createSession(
    ...
}

The Password Grant is often used for first-party "official" mobile apps. A user may wish to install such an app on two devices (eg: an iPhone and an iPod touch) and stay signed in on both of them.

With the existing functionality in the Password Grant, when the user signs in on their second device, deleteSession() will delete their first session from the oauth_sessions table, effectively signing them out from their first device.

If the call to deleteSession() was removed, then oauth_sessions could contain an unlimited number of sessions per user, enabling a user to stay signed in on an unlimited number of devices. Sessions can be deleted from oauth_sessions when:

  • The session doesn't have a refresh token, and the current time passes access_token_expires, or
  • The session does have a refresh token, and a very large amount of time (eg: a year) has passed since access_token_expires (it's very unlikely that the refresh token will be used a year after the access token has expired).

This is similar to Issue #25. The difference is:

  • Issue #25 concerns the Refresh Token Grant, creating multiple access tokens using one refresh token.
  • This issue concerns the Password Grant, creating multiple access tokens by signing in with username and password on multiple devices.

When will this project settle down?

Great project I'm loving it but honestly will there ever be a day where the repository hasn't moved or the namespace hasn't changed or the sponsor has changed so therefore you change the namespace. Is there any clear time where I can actually start using this library without having to spend time adapting to the new naming changes or repository changes?

Compile Error From Doc on Wiki for: Securing your API with OAuth 2.0

Alex,

I got a compile error when trying the "Hooking it all up" section. I couldn't edit your wiki so I figured I'd paste you the updated code. Here is the new code I have with what I have changed on lines 2 and 8.

        // Initiate the Request handler
        $request = new League\OAuth2\Server\Util\Request();

        // Initiate a new database connection
        $db = new League\OAuth2\Server\Storage\PDO\Db('mysql://user:pass@localhost/oauth');

        // Initiate the auth server with the models
        $server = new League\OAuth2\Server\Resource(
            new League\OAuth2\Server\Storage\PDO\Session($db)
        );

In addition I'm new to Laravel and I couldn't figure out how to get the composer oauth2-server package to get recognized.

May I suggest adding a section after composer to add:

// --------------------------------------------------------------
// The path to the composer vendors directory.
// --------------------------------------------------------------
$paths['composer'] = 'vendor';

and

// --------------------------------------------------------------
// Autoload composer vendors.
// --------------------------------------------------------------
require path('composer').DS.'autoload.php';

Missing `auto_approve` parameter

I started implementing the OAuth2 server by your tutorial (https://github.com/php-loep/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server) and found out that something is not right (or I need glasses).

The problem can be found here https://github.com/php-loep/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server#create-an-oauth-controller when you need to create the authorise endpoint. There is spoken of a auto_approve parameter in client_details however it is nowhere to be found!

I checked the ClientInterface who is (that I believe) responsible for providing that data. I looked at the docs at https://github.com/php-loep/oauth2-server/blob/master/src/League/OAuth2/Server/Storage/ClientInterface.php#L38 but there is also not spoken of an auto_approve.

I hope this is a valid problem and not me having a bad day =]

from where could i start

hi,

I downloaded the code to test the oauth over codeigniter framewrok , but I am really confused from where could I start . what I did is just importing the tables on database but then what to do with code ?!

Add support for token revocation

Add support for token revocation - http://tools.ietf.org/html/draft-ietf-oauth-revocation-06

Requires new method that will accept the following parameters by POST and will then use them to revoke an access token or refresh token:

  • token (REQUIRED) The token that the client wants to get revoked
  • token_type_hint (OPTIONAL) A hint about the type of the token submitted for revocation. Clients MAY pass this parameter in order to help the authorization server to optimize the token lookup. If the server is unable to locate the token using the given hint, it MUST extend its search accross all of its supported token types. An authorization server MAY ignore this parameter, particularly if it is able to detect the token type automatically. This specification defines two such values:
    • access_token
    • refresh_token
  • client_id (OPTIONAL)
  • client_secret (OPTIONAL)

If the client presents it's credentials it should be validated. If the client credentials are incorrect then respond with invalid_credentials error (from core spec).

If the server can't handle the presented token (if the token_type_hint parameter is used) then error with:

error=unsupported_token_type
&error_message=The authorization server does not support the  revocation of the presented token type.  I.e.  the client tried to revoke an access token on a server not supporting this feature.

The server should respond with 200 if the token revocation is successful or an invalid token is supplied.

Extension of the SessionInterface

I'm happy to see, that the dev version now contains the handling of the scope parameter, it basically works, but an important feature is missing.

The SessionInterface contains only one method "getScope", and this return the scope info or false is the scope is invalid. That's okay in simple cases, but it's not possible to differ between the owner type and the owner id.

Think about resource types that should only accessible for special clients. Theoretically every client can request every scope it wants, as there is no limitation on who has the right to use which scope.

I know that this behavior depends on the individual implementation, but at the moment there is no chance to implement such a limitation, as the SessionInterface has no information about the owner type and the owner id when the getScope method is called.

I modified the code and extended the getScope method as follows:
...
public function getScope($scope, $type, $typeId);
...

Also I extended the calls of this method in the ClientCredentials and Password Grant classes.

This solves the problem. Now I can create my own session storage class and return the scope information or false if the owner type and/or owner id is not allowed to use it (this information is saved in custom tables).

(Perhaps the parameters $type and $typeId are misleading, but this is how they are names in the SessionInterface.)

Would be great if you could implement this. Thanks.

Usage of phpunit.xml.dist instead the real config.

My proposal is :

We remove all real phpunit config (phpunit.xml) reference accross all branch, ignore it within .gitignore and just provide phpunit.xml.dist as default config that contains basic configuration. This way we won't enforce user, for example, to have the full code-coverage html generated each time they run phpunit (since the default phpunit.xml that distributed accross all branch will force them to do so).

Error when generating scope exception message

Hi,

I got the following error:

Access to undeclared static property: OAuth2\Grant\ClientCredentials::$exceptionMessages' in [...]\Oauth2\src\OAuth2\Grant\ClientCredentials.php (line115)

The same error exists in [...]\Oauth2\src\OAuth2\Grant\Password.php.

I replaced it with "AuthServer::getExceptionMessage('invalid_scope')" and this fixed the problem - but I saw, that sometime "$this->authServer->getExceptionMessage(...)" is used instead. I think that should be unified.

Limiting grants, clients and scopes

Following on from discussion in #20 and #21 the library needs to support the following features:

  • Limiting clients to certain scopes
  • Limiting clients to certain grants
  • Limiting scopes to certain grants (e.g. read only scopes over implicit grant)
  • Associating sessions with grant types

Should limiting clients to grants/scopes be opt-in (i.e. a client has to be whitelisted to use a particular grant/scope) or opt-out (i.e. blacklisted from using a particular grant/scope)?

I think it makes sense for the scopes to be opt-out of grants.

@philsturgeon @jacksonj04 @lapause @ziege any thoughts about this?

Required Classes not Distributed with Library

I'm going through the example for Securing an API with OAuth2 and I've run into a couple things:

  1. ezcDbFactory and ezcDbInstance (and whatever classes they require) are required but they don't seem to be distributed with the package when installed via composer. After some searching, it seems the libraries are downloadable here: http://ezcomponents.org.

Without adding all of the ezcomponents to my application, is there a way to get this OAuth2 library working, and better yet, are the ezcomponents actually required without having to rewrite your library's code?

  1. Small issue, but while I'm at it, on Securing an API with OAuth2 in the "Hooking it all up" section, the line:
$request = new League\OAuth2\Util\Request();

should be:

$request = new League\OAuth2\Server\Util\Request();

I couldn't figure out a way to edit or send a pull request for that.

Thanks!

OAuth1.0a support

This is a enhancement request (may be an issue)

Can OAuth1.0a is also supported? this will be helpful for sites which may not be using HTTPS yet and hence vulnerable to security threats

Scopes required by default?

When I read the RFC, I understood scopes to be optional, but now they are required by default. I think this makes things difficult for simple use cases - also, because a defined default scope is ignored in this case.

Suggestion:

  • Do not require scopes by default.
  • Check for default scopes if required but not set.

embedded user-agent support

Just want to ask if embedded user-agent is already supported out of the box?
I tried using the library and it seems that it implements external user-agent

Issue with isValid() function in Resource.php

It looks like a column name in the scopes table has changed from 'key' to 'scope'. The source code for Resource.php needs changing to reflect this

src/League/OAuth2/Server/Resource.php - Line: 197

Change:
$this->sessionScopes[] = $scope['key'];

To:
$this->sessionScopes[] = $scope['scope'];

Remove constructor from the RequestInterface

When integrating this library with Slim it would be nice to create a Request class that injects the Slim Request object and uses its built-in methods to get the get, post, etc... properties.

If the __construct is removed from the RequestInterface this would be a lot easier. This would probably also help with using Request objects from the other frameworks as well.

database table `users` not included in file `sql/mysql.sql`

Hi there!

oauth2-example-resource-server uses table users:

INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `phone`) VALUES (1,'Alex','Bilbie','[email protected]','01234567910'), (2,'Jane','Doe','[email protected]','01987654321');

but the table is not included in sql/mysql.sql of OAuth2. Could you add create table users in the sql?

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `firstname` varchar(255) NOT NULL DEFAULT '',
  `lastname` varchar(255) NOT NULL DEFAULT '',
  `email` varchar(255) NOT NULL DEFAULT '',
  `phone` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Thanks!

Refresh Token Grant - scope limitation and additional access tokens

Following the RFC, the implementation of the Refresh Token Grant isn't correct:

"Refresh tokens are issued [...] to obtain additional access tokens with identical or narrower scope." http://tools.ietf.org/html/rfc6749#section-1.5

  1. So it should be possible to change (limit) the scope of the existing session. At the moment the scope parameter is not used in the Refresh Token Grant. For example this is required for security reasons when you use multiple resource servers and don't want to use the same scope on each server.

  2. The current implementation doesn't create an "additional" access token, but replaces the existing one. I checked the oauth mailing list (http://list-archives.org/2012/10/31/oauth-ietf-org/oauth-wg-access-tokens-refresh-tokens-of-different-scopes/f/4229413633) and "additional" really means additional here, so you should be able to have multiple valid access tokens at the same time. But I'm not sure when to invalidate them - when creating an access token using another grant type?

Auto approve based on whether the user has approved the app before

I have seen the auto_approve parameter in the tutorial. But as far as I know it is retrieved from a specific field in the database.

What I want to know is whether there is any built in function to check whether the same user has approved the app with the same scope before and if not show the authorize page.

Do I have to write my own function to test that ?

404 Page Not Found

When i run this using RESTClient

http://localhost/myapi/oauth.php/authorise?
response_type=code&
client_id=I6Lh72kTItE6y29Ig607N74M7i21oyTo&
scope=Read+&state=x&
redirect_uri=http%3A%2F%2Flocalhost%2Fmyapi%2Flogin.php

i get

404 Page Not Found
The page you requested was not found.

after analyzing the code i found out that when i comment show_404($segments[0]); i am redirected to the default welcome page
the code below is from system/core/router.php

// If we've gotten this far it means that the URI does not correlate to a valid
    // controller class.  We will now see if there is an override
    if ( ! empty($this->routes['404_override']))
    {
        $x = explode('/', $this->routes['404_override']);

        $this->set_class($x[0]);
        $this->set_method(isset($x[1]) ? $x[1] : 'index');

        return $x;
    }


    // Nothing else to do at this point but show a 404
    show_404($segments[0]);
}

does anyone have ideas on what could be the problem

Multiple default scopes

The idea of default scopes is good in some situations, but if you really use scopes, you have multiple scopes that are assigned as default.

At the moment only one scope can be set as default. It would be possible to set an array, because the parameters are not checked, but the scripts calling this method expect an string at the moment.

Client secret never validated in AuthServer?

I may be missing something obvious here, and if so I apologize. Anyways the conclusion I've come to is that the client secret is never validated in AuthServer::checkAuthorizeParams(). I've secured my API according to the tutorials linked from the readme, and it does not matter which secret I send, I can retrieve an access token either way. Is it supposed to be like that?

Problem as I see it is in the code below, from AuthServer.php:298-299

// Validate client ID and redirect URI
$clientDetails = self::getStorage('client')->getClient($authParams['client_id'], null, $authParams['redirect_uri']);

The second parameter, client secret, is null and therefore never validated.

Oauth V2 Missing checkAuthoriseParams

Hi, recently i download from Composer i found public function checkAuthoriseParams()
is missing in AuthServer.php or there are new initialize

newAuthoriseRequest() also missing

OAuth2\Grant\AuthCode::__construct() must be an instance of OAuth2\AuthServer

If i call without $this->authserver it will prompt
Argument 1 passed to OAuth2\Grant\AuthCode::__construct() must be an instance of OAuth2\AuthServer, none given

$this->authserver->addGrantType(new \OAuth2\Grant\AuthCode());

WORK!!!!!!!!!!!!!!!
$this->authserver->addGrantType(new \OAuth2\Grant\AuthCode($this->authserver));

Bug in RefreshToken.php?

Was trying to add the Refresh Token option to your sample but just got a 500 error. Tracing it thru found on line 89 of RefreshToken.php a reference to client instead of session:

        // Validate refresh token
        $sessionId = AuthServer::getStorage('client')->validateRefreshToken(
            $authParams['refresh_token'],
            $authParams['client_id']
        );

Changing to this eliminated the 500 error:

        // Validate refresh token
        $sessionId = AuthServer::getStorage('session')->validateRefreshToken(
            $authParams['refresh_token'],
            $authParams['client_id']
        );

Composer installation

There is a small error in the composer package name given in the readme, the name is staded to be "league/oauth2-server" while the actual name is "league/oauth2server"
(source: https://packagist.org/packages/league/oauth2server)

Also, when installing there might be a broken dependency:
league/oauth2server 2.0.5 requires zetacomponents/database dev-master -> no matching package found.

(I'm installing with "require-dev")

Example of implicit grant?

Do you have an example of the recommended way to use implicit grants with this server?

It seems like most of the authorization_code example in https://github.com/php-loep/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server can be used. However, there are two points where I'm a little confused about the best approach:

  • In action_authorise, where it says "Generate an authorization code", this seems like the right place to check the grant type. Should we just check for Session::get('response_type') === "token", and if it's set, call issueAccessToken instead of newAuthoriseRequest?
  • If so, the expected argument to issueAccessToken doesn't seem right. It's looking for an array of POST fields. But in this case, you won't be making a separate POST request for the access token. So it will fail because there's no grant_type=implicit field. Of course, I can manually construct this array, and pass it in to issueAccessToken myself. But that and the other required parameters should probably be documented, since it's not part of the OAuth2 spec.

Library packed with Codeigniter

this is code Ouath2 Controller. I already include "zetacomponents/database": "1.4.6" in composer.json

<?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();

            // Save the verified parameters to the user's session
            $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 "error";
            // Throw an error here which says what the problem is with the
            //  auth params

        } catch (Exception $e) {
           // I ALWAYS IN HERE
            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
            }
        }

        // Process the sign-in form submission
        if ($this->input->get_post('signin') != null) {
            try {

                // Get username
                $u = $this->input->get('username');
                if ($u == null || trim($u) == '') {
                    throw new Exception('please enter your username.');
                }

                // Get password
                $p = $this->input->get('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

            } 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 "login form";
        }
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.