Coder Social home page Coder Social logo

yii2-oauth2-server's Introduction

yii2-oauth2-server

A wrapper for implementing an OAuth2 Server(https://github.com/bshaffer/oauth2-server-php)

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist filsh/yii2-oauth2-server "*"

or add

"filsh/yii2-oauth2-server": "^2.0"

to the require section of your composer.json.

To use this extension, simply add the following code in your application configuration:

'bootstrap' => ['oauth2'],
'modules' => [
    'oauth2' => [
        'class' => 'filsh\yii2\oauth2server\Module',
        'tokenParamName' => 'accessToken',
        'tokenAccessLifetime' => 3600 * 24,
        'storageMap' => [
            'user_credentials' => 'common\models\User',
        ],
        'grantTypes' => [
            'user_credentials' => [
                'class' => 'OAuth2\GrantType\UserCredentials',
            ],
            'refresh_token' => [
                'class' => 'OAuth2\GrantType\RefreshToken',
                'always_issue_new_refresh_token' => true
            ]
        ]
    ]
]

common\models\User - user model implementing an interface \OAuth2\Storage\UserCredentialsInterface, so the oauth2 credentials data stored in user table

The next step you should run migration

yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/src/migrations

this migration creates the oauth2 database scheme and insert test user credentials testclient:testpass for http://fake/

add url rule to urlManager

'urlManager' => [
    'rules' => [
        'POST oauth2/<action:\w+>' => 'oauth2/rest/<action>',
        ...
    ]
]

Configuration

You can pass additional OAuth2 Server options by setting options property on the module. These options configure as the underlying OAuth2 Server also as various parts/components of bshaffer/oauth2-server-php. As an example, you can configure authorization code lifetime in a response by setting auth_code_lifetime option. Some of them are implemented as standalone properties on the module: tokenParamName => use_jwt_access_tokens, tokenAccessLifetime => token_param_name, useJwtToken => access_lifetime. Full list of options are supported by the underlying OAuth2 Server main component - source code. Options for various components spread across bshaffer/oauth2-server-php source code.

Usage

To use this extension, simply add the behaviors for your base controller:

use yii\helpers\ArrayHelper;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;
use filsh\yii2\oauth2server\filters\auth\CompositeAuth;

class Controller extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class' => CompositeAuth::className(),
                'authMethods' => [
                    ['class' => HttpBearerAuth::className()],
                    ['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
                ]
            ],
            'exceptionFilter' => [
                'class' => ErrorToExceptionFilter::className()
            ],
        ]);
    }
}

Create action authorize in site controller for Authorization Code

https://api.mysite.com/authorize?response_type=code&client_id=TestClient&redirect_uri=https://fake/

see more

/**
 * SiteController
 */
class SiteController extends Controller
{
    /**
     * @return mixed
     */
    public function actionAuthorize()
    {
        if (Yii::$app->getUser()->getIsGuest())
            return $this->redirect('login');
    
        /** @var $module \filsh\yii2\oauth2server\Module */
        $module = Yii::$app->getModule('oauth2');
        $response = $module->getServer()->handleAuthorizeRequest(null, null, !Yii::$app->getUser()->getIsGuest(), Yii::$app->getUser()->getId());
    
        /** @var object $response \OAuth2\Response */
        Yii::$app->getResponse()->format = \yii\web\Response::FORMAT_JSON;
    
        return $response->getParameters();
    }
}

Also, if you set allow_implicit => true in the options property of the module, you can use Implicit Grant Type - see more

Request example:

https://api.mysite.com/authorize?response_type=token&client_id=TestClient&redirect_uri=https://fake/cb

With redirect response:

https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600

JWT Tokens

If you want to get Json Web Token (JWT) instead of conventional token, you will need to set 'useJwtToken' => true in module and then define two more configurations: 'public_key' => 'app\storage\PublicKeyStorage' which is the class that implements PublickKeyInterface and 'access_token' => 'OAuth2\Storage\JwtAccessToken' which implements JwtAccessTokenInterface.php

For Oauth2 base library provides the default access_token which works great except. Just use it and everything will be fine.

and public_key

<?php
namespace app\storage;

class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{


    private $pbk =  null;
    private $pvk =  null; 
    
    public function __construct()
    {
        $this->pvk =  file_get_contents('privkey.pem', true);
        $this->pbk =  file_get_contents('pubkey.pem', true); 
    }

    public function getPublicKey($client_id = null){ 
        return  $this->pbk;
    }

    public function getPrivateKey($client_id = null){ 
        return  $this->pvk;
    }

    public function getEncryptionAlgorithm($client_id = null){
        return 'RS256';
    }

}

For more, see https://github.com/bshaffer/oauth2-server-php

Authors & Contributors

The original author of this package Igor Maliy . At the time the project maintainer is Vardan Pogosian.

yii2-oauth2-server's People

Contributors

brutto avatar damiandennis avatar dareen avatar filsh avatar freezy-sk avatar hector-del-rio avatar hiqsol avatar jcherniak avatar lisps avatar mtangoo avatar pdanzinger avatar pelegrin avatar royxiang avatar ruslanbes avatar rzani avatar sasha-ch avatar shcherbanich avatar simonsoftware avatar tibee avatar tuxoff avatar varp avatar wilberto-dzul avatar zacksleo 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

yii2-oauth2-server's Issues

Migration does not support PostgreSQL

The syntax of the migration script does not support Postgresql databases.

...
'PRIMARY KEY (client_id)'
...
'expires' => Schema::TYPE_TIMESTAMP . ' NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
...

Exception: error loading class 'user_credentials'

After this commit 6d4b6be the Module is not working anymore for me.

It is throwing exception on line:

        foreach(array_keys($this->storageMap) as $name) {
            $storages[$name] = \Yii::$container->get($name);
        }

Trying to get $name = 'user_credentials' from the container.

The method public function createStorages() was removed from the Module class.

Stack:

{
  "name": "Exception",
  "message": "Class user_credentials does not exist",
  "code": -1,
  "type": "ReflectionException",
  "file": "/Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/di/Container.php",
  "line": 415,
  "stack-trace": [
    "#0 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/di/Container.php(415): ReflectionClass->__construct('user_credential...')",
    "#1 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/di/Container.php(358): yii\di\Container->getDependencies('user_credential...')",
    "#2 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/di/Container.php(151): yii\di\Container->build('user_credential...', Array, Array)",
    "#3 /Users/admin/Sites/elo-jur-dico-web/vendor/filsh/yii2-oauth2-server/Module.php(100): yii\di\Container->get('user_credential...')",
    "#4 /Users/admin/Sites/elo-jur-dico-web/vendor/filsh/yii2-oauth2-server/filters/auth/CompositeAuth.php(14): filsh\yii2\oauth2server\Module->getServer()",
    "#5 /Users/admin/Sites/elo-jur-dico-web/common/classes/CompositeAuth.php(15): filsh\yii2\oauth2server\filters\auth\CompositeAuth->beforeAction(Object(yii\base\InlineAction))",
    "#6 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/base/ActionFilter.php(70): common\classes\CompositeAuth->beforeAction(Object(yii\base\InlineAction))",
    "#7 [internal function]: yii\base\ActionFilter->beforeFilter(Object(yii\base\ActionEvent))",
    "#8 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/base/Component.php(541): call_user_func(Array, Object(yii\base\ActionEvent))",
    "#9 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/base/Controller.php(269): yii\base\Component->trigger('beforeAction', Object(yii\base\ActionEvent))",
    "#10 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/web/Controller.php(121): yii\base\Controller->beforeAction(Object(yii\base\InlineAction))",
    "#11 /Users/admin/Sites/elo-jur-dico-web/frontend/controllers/api/v1/EloRestController.php(44): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))",
    "#12 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/base/Controller.php(152): frontend\controllers\api\v1\EloRestController->beforeAction(Object(yii\base\InlineAction))",
    "#13 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/base/Module.php(454): yii\base\Controller->runAction('escritorio', Array)",
    "#14 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/web/Application.php(84): yii\base\Module->runAction('api/v1/escritor...', Array)",
    "#15 /Users/admin/Sites/elo-jur-dico-web/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))",
    "#16 /Users/admin/Sites/elo-jur-dico-web/frontend/web/index.php(18): yii\base\Application->run()",
    "#17 {main}"
  ]
}

Config:

'modules' => [
        'oauth2' => [
            'class' => 'filsh\yii2\oauth2server\Module',
           'tokenParamName' => 'accessToken',
           'tokenAccessLifetime' => 3600 * 24,
            'storageMap' => [
                'user_credentials' => 'common\models\UserOAuth'
            ],
            'grantTypes' => [
                'client_credentials' => [
                    'class' => 'OAuth2\GrantType\ClientCredentials',
                    'allow_public_clients' => false
                ],
                'user_credentials' => [
                    'class' => 'OAuth2\GrantType\UserCredentials'
                ],
                'refresh_token' => [
                    'class' => 'OAuth2\GrantType\RefreshToken',
                    'always_issue_new_refresh_token' => true
                ]
            ]
        ]
    ],

Grant types and oauth_public_keys missing

Hello!

In file Module.php on line 39-42:

 $server->addGrantType(new \OAuth2\GrantType\UserCredentials($storages['user_credentials']));
 $server->addGrantType(new \OAuth2\GrantType\RefreshToken($storages['refresh_token'], [
        'always_issue_new_refresh_token' => true
]));

Only these 2 grant types are added to server. Without overriding this class, I cannot add other grant types that are already supported by bshaffer/oauth2-server-php.

  • Why is it neccessary to wire these 2 grant types into this file, as the default ones would be sufficient of bshaffer/oauth2-server-php, and these could be restricted in table oauth_clients.
  • In your migration there is a sample row in oauth_clients table, having grant type client_credentials set, but because of the aboves, it does not work...
curl -v -X POST -u testclient:testpass "http://api.test.domain/oauth2/token" -d 'grant_type=client_credentials'

{"name":"Bad Request","message":"Grant type \"client_credentials\" not supported","code":0,"status":400,"type":"yii\\web\\HttpException"}
  • Why is the table oauth_public_keys missing from your migration?
CREATE TABLE oauth_public_keys (
client_id VARCHAR(80),
public_key VARCHAR(2000),
private_key VARCHAR(2000),
encryption_algorithm VARCHAR(100) DEFAULT "RS256"
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Thank you!

Problems with v2.0.1

1. Is v2.0.1 release supposed to be used? I failed to make it working :( While master branch version works just fine.

2. I don't get the idea of removing $options from Module and substition it with tokenParamName and others and then converting it back with:

    [
        'token_param_name' => $this->tokenParamName,
        'access_lifetime' => $this->tokenAccessLifetime,
        'refresh_token_lifetime' => $this->tokenRefreshLifetime,
        /** add more ... */
    ],  

I've counted - there are 34 config options in bshaffer/oauth2-server-php
Are you going to add them all?And keep in sync with bshaffer all the time?
Isn't your package supposed to be a thin wrapper?

For example I use 'enforce_state' option, I could add it to Module.php. But then it needs Pull Request
and all the procedure to get working. While $options just works, and anybody can add
any of currently available 34 options and any added in future.

3. Storage map initialization doesn't work.
Now it is:

            foreach(array_keys($this->storageMap) as $name) {
                $storages[$name] = \Yii::$container->get($name);
            }

while the storageMap config is like this:

            'storageMap' => [
                'user_credentials'  => 'common\models\User',
            ],

So it tries:

Yii::$container->get('user_credentials')

which ends with error:

Class user_credentials does not exist

Shouldn't initialization be like it was previously:

            foreach($this->storageMap as $name => $class) {
                $storages[$name] = \Yii::$container->get($class);
            }

It does make sense and seems working.

Thank in advance for any help :)

Unable to install with composer due to stability level

My fresh installation of yii2-advanced does not accept the current stability level of this package:

composer require --prefer-dist filsh/yii2-oauth2-server "*"

does not work. Instead I used:

composer require --prefer-dist filsh/yii2-oauth2-server "@dev"

Controller Token Behavior

After studiying the @mtangoo library based in this module and the specification in the documentation of this module, I have a question about the use of CompositeAuth::className() as an authenticator.

It's supposed to be able to stop a query without token, but it only checks that in the beforeAction step. Also it doesn't throw an error or anything. It only checks if token is valid and if it is or isn't, continues the check calling in the example two authmethods that check the access token in the declared component user model that maybe or maybe not have a valid loginByAccessToken call with the oauth token. (code comes a little confusing here, sorry). Shouldn't be better to implement a more direct approach compatible with oauth authentication based ONLY in token checking and, if we want to add something more (which in theory would be breaking the oauth2 standard) have an option for that?

Usage Example

Hello, thanks for the good work on this module it looks cool and professional :)

Can you please update the Usage example as it is not very clear.

I added the behaviors on my SiteController and seems to work,
but can not manage to send a proper requests I always get this error:

"You are requesting with an invalid credential."

Is there anything special about the controller or the params to make it work ?

Add translation support for the models

The models do not use Yii:t() which would be useful, for using the models in another language.

This would for example in OauthAccessTokens change:

public function attributeLabels()
{
    return [
        'access_token' => 'Access Token',
        'client_id' => 'Client ID',
        'user_id' => 'User ID',
        'expires' => 'Expires',
        'scope' => 'Scope',
    ];
}

to

public function attributeLabels()
{
    return [
        'access_token' => Yii::t('oauth2-server', 'Access Token'),
        'client_id' => Yii::t('oauth2-server', 'Client ID'),
        'user_id' => Yii::t('oauth2-server', 'User ID'),
        'expires' => Yii::t('oauth2-server', 'Expires'),
        'scope' => Yii::t('oauth2-server', 'Scope'),
    ];
}

Proper Documentation...

I have read every post... but couldn't find step-by-step tutorial or examples how to use this extension :( Dear fellow developers, is there anyone who have figured out?

Any help appreciated :)

p.s. the problem is "You are requesting with an invalid credential."
(the request url is "https://localhost/accounts/index?grant_type=password&username=test&password=test&client_id=testclient&client_secret=testpass")

I tried https://localhost/oauth2/token?grant_type=password&username=test&password=test&client_id=testclient&client_secret=testpass and it gave me 404 Error...

Yes I have included "'POST oauth2/action:w+' => 'oauth2/default/'," in my urlmanager...

Migration error

When applying of migration there is an error

PHP Strict Warning 'yii\base\ErrorException' with message 'Declaration of m140501_075311_add_oauth2_server::primaryKey() should be compatible with yii\db\Migration::primaryKey($length = NULL)'

Need set Null on default in primaryKey function public function primaryKey($columns = null) or rename function

Usage Issues

I'm trying to use this extension but I'm getting the error below:

Call to a member function getServer() on a non-object

Any help?

access token 404

version 2.0.1 installs - bshaffer/oauth2-server-php (v1.7.1)
and in yii2 advanced template I get a 404 error when trying to generate an access token

2015-09-07 13:10:59 [127.0.0.1][-][-][error][yii\web\HttpException:404] exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "oauth2/default/token".' in /home/user/project/devel.local/vendor/yiisoft/yii2/base/Module.php:461
Stack trace:
#0 /home/user/project/devel.local/vendor/yiisoft/yii2/web/Application.php(84): yii\base\Module->runAction('oauth2/default/...', Array)
#1 /home/user/project/devel.local/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#2 /home/user/project/devel.local/api/www/index.php(17): yii\base\Application->run()
#3 {main}

Next exception 'yii\web\NotFoundHttpException' with message 'Page not found.' in /home/user/project/devel.local/vendor/yiisoft/yii2/web/Application.php:96
Stack trace:
#0 /home/user/project/devel.local/vendor/yiisoft/yii2/base/Application.php(375): yii\

my bad composer.json composer config:

"minimum-stability": "stable",
"require": {
    "php": ">=5.4.0",
    "yiisoft/yii2": ">=2.0.6",
    "yiisoft/yii2-bootstrap": "*",
    "yiisoft/yii2-swiftmailer": "*",
    "dektrium/yii2-user": "0.9.*@dev",
    "dektrium/yii2-rbac": "dev-master",
    "filsh/yii2-oauth2-server": "~2.0.1"
},

everything works fine with composer.json:

"minimum-stability": "stable",
"require": {
    "php": ">=5.4.0",
    "yiisoft/yii2": ">=2.0.6",
    "yiisoft/yii2-bootstrap": "*",
    "yiisoft/yii2-swiftmailer": "*",
    "dektrium/yii2-user": "0.9.*@dev",
    "dektrium/yii2-rbac": "dev-master",
    "filsh/yii2-oauth2-server": "dev-master"
},

When a new stable version is released?

Migrations with SQL Server

Migrations seems to be not working with SQL Server as type of Timestamp should be automatic not explicitly put [1]. It would be great to change field to something else like datetime or remove explicit insertion at

Yii Migration Tool (based on Yii v2.0.6)

Total 1 new migration to be applied:
        m140501_075311_add_oauth2_server

Apply the above migration? (yes|no) [no]:y
*** applying m140501_075311_add_oauth2_server
    > create table {{%oauth_clients}} ... done (time: 0.032s)
    > create table {{%oauth_access_tokens}} ...Exception: SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Defaults cannot be created on columns of data type timestamp. Table 'oauth_access_tokens', column 'expires'.
The SQL being executed was: CREATE TABLE [oauth_access_tokens] (
        [access_token] varchar(40) NOT NULL,
        [client_id] varchar(32) NOT NULL,
        [user_id] int DEFAULT NULL,
        [expires] timestamp NOT NULL DEFAULT 'now' ,
        [scope] varchar(2000) DEFAULT NULL,
        PRIMARY KEY ([access_token]),
         FOREIGN KEY ([client_id]) REFERENCES [oauth_clients] ([client_id]) ON DELETE CASCADE ON UPDATE CASCADE
)\n*** failed to apply m140501_075311_add_oauth2_server (time: 0.276s)


Migration failed. The rest of the migrations are canceled.

I have done some modifications here (Hope to do PR when I have time and meanwhile I share them here)

public function up()
    {
        $tableOptions = null;        

        $now = null;
        $on_update_now  = null;        
        $timestamp = null;

        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';

            $now = $this->mysql('CURRENT_TIMESTAMP',"'now'");
            $on_update_now  = $this->mysql("ON UPDATE $now");
            $timestamp = Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now";
        }
        else if($this->db->driverName === 'sqlsrv'){
            //set values for SQL Server
            $timestamp = Schema::TYPE_TIMESTAMP;
        }

        $transaction = $this->db->beginTransaction();
        try {
            $this->createTable('{{%oauth_clients}}', [
                'client_id' => Schema::TYPE_STRING . '(32) NOT NULL',
                'client_secret' => Schema::TYPE_STRING . '(32) DEFAULT NULL',
                'redirect_uri' => Schema::TYPE_STRING . '(1000) NOT NULL',
                'grant_types' => Schema::TYPE_STRING . '(100) NOT NULL',
                'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL',
                'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
                $this->primaryKey('client_id'),
            ], $tableOptions);

            $this->createTable('{{%oauth_access_tokens}}', [
                'access_token' => Schema::TYPE_STRING . '(40) NOT NULL',
                'client_id' => Schema::TYPE_STRING . '(32) NOT NULL',
                'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
                'expires' => $timestamp,
                'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL',
                $this->primaryKey('access_token'),
                $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'),
            ], $tableOptions);

            $this->createTable('{{%oauth_refresh_tokens}}', [
                'refresh_token' => Schema::TYPE_STRING . '(40) NOT NULL',
                'client_id' => Schema::TYPE_STRING . '(32) NOT NULL',
                'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
                'expires' => $timestamp,
                'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL',
                $this->primaryKey('refresh_token'),
                $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'),
            ], $tableOptions);

            $this->createTable('{{%oauth_authorization_codes}}', [
                'authorization_code' => Schema::TYPE_STRING . '(40) NOT NULL',
                'client_id' => Schema::TYPE_STRING . '(32) NOT NULL',
                'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
                'redirect_uri' => Schema::TYPE_STRING . '(1000) NOT NULL',
                'expires' => $timestamp,
                'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL',
                $this->primaryKey('authorization_code'),
                $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'),
            ], $tableOptions);

            $this->createTable('{{%oauth_scopes}}', [
                'scope' => Schema::TYPE_STRING . '(2000) NOT NULL',
                'is_default' => Schema::TYPE_BOOLEAN . ' NOT NULL',
            ], $tableOptions);

            $this->createTable('{{%oauth_jwt}}', [
                'client_id' => Schema::TYPE_STRING . '(32) NOT NULL',
                'subject' => Schema::TYPE_STRING . '(80) DEFAULT NULL',
                'public_key' => Schema::TYPE_STRING . '(2000) DEFAULT NULL',
                $this->primaryKey('client_id'),
            ], $tableOptions);

            $this->createTable('{{%oauth_users}}', [
                'username' => Schema::TYPE_STRING . '(255) NOT NULL',
                'password' => Schema::TYPE_STRING . '(2000) DEFAULT NULL',
                'first_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL',
                'last_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL',
                $this->primaryKey('username'),
            ], $tableOptions);

            $this->createTable('{{%oauth_public_keys}}', [
                'client_id' => Schema::TYPE_STRING . '(255) NOT NULL',
                'public_key' => Schema::TYPE_STRING . '(2000) DEFAULT NULL',
                'private_key' => Schema::TYPE_STRING . '(2000) DEFAULT NULL',
                'encryption_algorithm' => Schema::TYPE_STRING . '(100) DEFAULT \'RS256\'',
            ], $tableOptions);

           // .......................
}

[1] - http://stackoverflow.com/questions/10262426/sql-server-cannot-insert-an-explicit-value-into-a-timestamp-column

POST oauth2/token method to GET oauth2/token

Hello fellow developers...
Is it possible to authorize via GET request (p.s. oauth2/token?grant_type=password&username=test&password=test&client_id=testclient&client_secret=testpass) ?

When I try to auth via GET it returns me:
{"name":"Method Not Allowed","message":"The request method must be POST when requesting an access token","code":0,"status":405,"type":"filsh\yii2\oauth2server\exceptions\HttpException"}

I am facing problems with implementing client-side... It seems most of the ready libraries for android supports authorization via GET request...

Thanks in advance :)

FR: Add $scope check to CompositeAuth

Filter CompositeAuth currently has no ability to check scope. It whoud be great to add such ability.

Future usage example:

public function behaviors()
{
    return [
        'authenticator' => [
            'class' => 'filsh\yii2\oauth2server\filters\auth\CompositeAuth',
            'scopeRequired' => 'foobar',
        ],
    ];
}

Setting unknown property: filsh\yii2\oauth2server\Module::options

After updating yo yii2.0.6 - when I run my application - I get the following error:

Setting unknown property: filsh\yii2\oauth2server\Module::options

The issue is due the

'options' =>[
    'token_param_name' => 'access_token',
    'access_lifetime' => 3600 * 24
]

setting in the application/config/common.php under the oauth2 module which was done according to README.md

Установка

Здравствуйте. Подскажите, пожалуйста, как правильно установить модуль? Этот модуль только для "yii2-app-advanced" приложений?

filsh\yii2\oauth2server\storage\Pdo

filsh\yii2\oauth2server\Module

public function getServer($force = false, $config=array())
{
if($this->_server === null || $force === true) {
$storages = [];
foreach($this->storageMap as $name => $value) {
$storages[$name] = \Yii::$container->get($name, array(),$config);
}
$server = new \OAuth2\Server($storages, $this->options);

        foreach($this->grantTypes as $name => $options) {
            if(!isset($storages[$name]) || empty($options['class'])) {
                throw new \yii\base\InvalidConfigException('Invalid grant types configuration.');
            }

            $class = $options['class'];
            unset($options['class']);

            $reflection = new \ReflectionClass($class);
            $config = array_merge([0 => $storages[$name]], [$options]);

            $instance = $reflection->newInstanceArgs($config);
            $server->addGrantType($instance);
        }

        $this->_server = $server;
    }
    return $this->_server;
}

this config can merge OAuth2\Storage\Pdo class config property

$this->config = array_merge(array(
'client_table' => 'oauth_clients',
'access_token_table' => 'oauth_access_tokens',
'refresh_token_table' => 'oauth_refresh_tokens',
'code_table' => 'oauth_authorization_codes',
'user_table' => 'oauth_users',
'jwt_table' => 'auth_jwt',
'scope_table' => 'oauth_scopes',
'public_key_table' => 'oauth_public_keys',
), $config);

because my database table has prefix cp_

Add support for OPTIONS requests

So far i have to create a custom controller to handle OPTIONS requests on oauth endpoint:

            'rules'               => [
                'POST oauth2/<action:\w+>/'    => 'oauth2/default/<action>',
                'OPTIONS oauth2/<action:\w+>/' => 'site/oauthOptions',

Where did handleAuthorizeRequest go?

I'm not really sure what happened, but where did the handleAuthorizeRequest method in Module.php go in the 2.0.1 branch? It seems to be removed in the JWT commits a few day ago. Why?

Grant type problem

After I installed the module and applied all the things what was writen in the in the documentation, I recevive "The grant type was not specified in the request" error when I pass the username/password to "/oauth2/token"

Few questions

Hi,

Thanks for great extension. have couple of doubts, Hope you help me clear those :

  1. How to handle api request which has expired token?
  2. How to validate token manually in some cases?
  3. How to expire token forcefully?

Thanks

Customize oauth2/token method

Hello, now i want to customize oauth2/token method, so can i do. I want to show more information with response message. thanks

dynamic storageMaps and modelMaps

We use the yii2-oauth2-server with mongoDB. Originally we used it when it has not any version number. We had to apply some modifications and overrides to make it work. Until now it works well, but today updated the version to 2.0 and I see that I'm forced to use all these storageMaps:
access_token,authorization_code,client_credentials,client,refresh_token,user_credentials,public_key,jwt_bearer,scope
and all these modelMaps:
OauthClients,OauthAccessTokens,OauthAuthorizationCodes,OauthRefreshTokens,OauthScopes
because these are loaded into protected arrays ($_modelMap,$_storageMap) in Bootstrap.php and I can just override them with my MongoDB Storage class. That's why I can not skip which are not used, for example in my actual project we just need:
access_token
client
refresh_token
user_credentials
OauthAccessTokens
OauthRefreshTokens
All the others are useless and I don't wanna create fake classes just to handle these problem.

Migration command is incorrect

$ ./yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/migrations/m140501_075311_add_oauth2_server.php
PHP Warning 'yii\base\ErrorException' with message 'mkdir(): File exists'

Should be

$ ./yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/migrations

without php file, Yii will ask

Total 1 new migration to be applied:
        m140501_075311_add_oauth2_server

Apply the above migration? (yes|no) [no]:yes

Own grantType for federation auth

Actually it is quite cool to use this as an auth service that handles different apps or resource servers. I want to use it as an central auth instance. So the only point that is missing actually for it is that I can login/register alternatively with Facebook or Google or something like this at the Auth Service.

So actually I need a new grant_type or? that takes up the signed_request that is returned e.g. by FaceBook and validated so that I can somehow create the new token for our system.

So add new granttype to config and storage map e.g.:

           'storageMap' => [
                'user_credentials' => 'api\models\User',
                'federation_credentials' => 'api\models\Auth'
            ],
           'grantTypes' => [
                'client_credentials' => [
                    'class' => 'OAuth2\GrantType\ClientCredentials',
                    'allow_public_clients' => false
                ],
                'user_credentials' => [
                    'class' => 'OAuth2\GrantType\UserCredentials'
                ],
                'refresh_token' => [
                    'class' => 'OAuth2\GrantType\RefreshToken',
                    'always_issue_new_refresh_token' => true
                ],
                'federation_credentials' => [
                    'class' => 'api\components\auth\ExternalCredentials'
                ]
            ],

ExternalCredentials may look like this? (could not test it):

namespace api\components\auth;

use OAuth2\GrantType\GrantTypeInterface;
use OAuth2\RequestInterface;
use OAuth2\ResponseInterface;
use OAuth2\ResponseType\AccessTokenInterface;

class ExternalCredentials implements GrantTypeInterface
{
    private $userInfo;

    protected $storage;

    public function __construct(ExternalCredentialsInterface $storage)
    {
        $this->storage = $storage;
    }

    public function getQuerystringIdentifier()
    {
        return 'signed_request';
    }

    public function validateRequest(RequestInterface $request, ResponseInterface $response)
    {
        if (!$request->request("signed_request")) {
            $response->setError(400, 'invalid_request', 'Missing parameters: "username" and "password" required');

            return null;
        }

        if (!$this->storage->checkUserCredentials($request->request("signed_request"))) {
            $response->setError(401, 'invalid_grant', 'Invalid signed request');

            return null;
        }

        $userInfo = $this->storage->getUserDetails($request->request("signed_request"));

        if (empty($userInfo)) {
            $response->setError(400, 'invalid_grant', 'Unable to retrieve user information');

            return null;
        }

        if (!isset($userInfo['user_id'])) {
            throw new \LogicException("you must set the user_id on the array returned by getUserDetails");
        }

        $this->userInfo = $userInfo;

        return true;
    }

    public function getClientId()
    {
        return null;
    }

    public function getUserId()
    {
        return $this->userInfo['user_id'];
    }

    public function getScope()
    {
        return isset($this->userInfo['scope']) ? $this->userInfo['scope'] : null;
    }

    public function createAccessToken(AccessTokenInterface $accessToken, $client_id, $user_id, $scope)
    {
        return $accessToken->createAccessToken($client_id, $user_id, $scope);
    }
}

And I have to manually add to filsh's and bshaffer's repo the new grant type? This seems not like the perfect way. How can I add my own grant_type?

function findIdentityByAccessToken

Hello,

I have a question about the following function:

public static function findIdentityByAccessToken($token, $type = null)
    {
        /** @var \filsh\yii2\oauth2server\Module $module */
        $module = Yii::$app->getModule('oauth2');
        $token = $module->getServer()->getResourceController()->getToken();
        return !empty($token['user_id'])
                    ? static::findIdentity($token['user_id'])
                    : null;
    }

What´s the point of sending $token by parameter if it´s overwritten on that line, before using it?

$token = $module->getServer()->getResourceController()->getToken();

QueryParamAuth access_token doesn't work

If I do a request with an access_token as GET-param it gives me the error: Malformed auth header. This may because I have to send the client-credentials via Basic Auth which does set the Authorization header, which is checked if there is a Bearer token, which isn't. It also doesn't work with a Bearer token and Basic Auth because of that.

My only possible solution was to send the client-credentials via GET/POST parameters and a Bearer token. It also doesn't work with a access_token param instead of the Bearer token.

Token URL for 2.0.1 not working

Installing server yii2-oauth2-server version dev-master (1.0), Token can be fetched from

/oauth2/default/token

Installing version 2.0.1, no url works anymore. I see the new controller is RestController.php, but anyway all url fails:

/oauth2/default/token
/oauth2/rest/token
/rest/token
/default/token

upgrading from 1 to 2 problems

Hi,

Simply putting v2 in composer broke our app with this:

Setting unknown property: filsh\yii2\oauth2server\Module::options

Any clue?

For help....

Can you give us a tutorial about how to use it, thanks!

Error when using tablePrefix

Filsh,

When using tablePrefix, migrations creates all tables correctly, but the Pdo.php is not overwriting the $config variable from OAuth2\Storage\Pdo.php.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.oauth_access_tokens' doesn't exist

Thanks for your work.

Add support for option refresh_token_lifetime

Could you add support for the refresh_token_lifetime option for the Refresh Token grant type?

I thought something like:

class Module extends \yii\base\Module
{
    // ...

    public $refreshTokenLifetime = 2419200;

    // ...

    public function getServer($force = false)
    {
        // ...
            $server->addGrantType(new \OAuth2\GrantType\RefreshToken($storages['refresh_token'], [
                'always_issue_new_refresh_token' => true,
                'refresh_token_lifetime' => $this->refreshTokenLifetime,
            ]));

            // ...

And could be configured in the config file:

'oauth2' => [
            'class' => 'filsh\yii2\oauth2server\Module',
            'options' => [
                'token_param_name' => 'access_token',
                'access_lifetime' => 3600 * 24,
                'allow_implicit' => true,
                'enforce_state' => false,
                'enforce_redirect' => true,
            ],
            'storageMap' => [
                'user_credentials' => 'api\modules\v1\models\User'
            ],
            'refreshTokenLifetime' => 2419200,
        ],

Lets Build Documentation

There is no documentation and no one seems to care. so here is an issue where anyone can share a bit he knows and code snippets. Then I will Put them together into Nice documentation. Here are loose leading point (they aren't rules so feel free to break them)

  1. Components of the extension (Pick one and explain what it does)
  2. How does the grant Process work
  3. Using Different grants with extension (see [1] for types of grants)
  4. Different code snippets (explain in summary what it does)

I hope you guys will help making this extension better

Add support of CORS headers

I had to override the DefaultController to add CORS behavior:

<?php

namespace app\controllers;

use app\extensions\Cors;
use filsh\yii2\oauth2server\controllers\DefaultController;
use yii;

class OauthController extends DefaultController
{

    public function init(){
        parent::init();
        $this->module = Yii::$app->getModule('oauth2');
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            'corsFilter' => [
                'class' => Cors::className() // some custom config inside the class
            ],
        ]);
    }

    public function actionOptions()
    {

        Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', ['OPTIONS', 'POST']));

    }

}

Without that each oauth request will fail because of no CORS headers

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.