ikaras / yii2-oauth2-rest-template Goto Github PK
View Code? Open in Web Editor NEWYii2 Rest APi Template with OAuth2 server
License: MIT License
Yii2 Rest APi Template with OAuth2 server
License: MIT License
Hello, i try to call metho findIdentityByAccessToken but it return null, How can i fix it. thank.
I updated my yii2 version and I get the following error
Setting unknown property: filsh\yii2\oauth2server\Module::options
I followed the instructions and everything is going fine / installation/ db connection / migration than I tried this in terminal:
curl -i -H "Accept:application/json" -H "Content-Type:application/json" "http://api.loc/v1/products"
Maybe I am just foolish but I do not get to the point why it cannot find something.
The only thing that is different that I do not use api.loc instead I use the real path after localhost to the directory.
i got error
PHP Fatal Error – yii\base\ErrorException
Call to undefined method OAuth2\ClientAssertionType\HttpBasic::className()
use OAuth2\ClientAssertionType\HttpBasic;
74 /**
* @inheritdoc
*/
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'class' => CompositeAuth::className(),
'authMethods' => [
['class' => HttpBasic::className()],
// ['class' => HttpBearerAuth::className()],
['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
]
],
'exceptionFilter' => [
'class' => ErrorToExceptionFilter::className()
],
]);
}
2. yii\base\ErrorHandler::handleFatalError()
Hey, another thing I'm tackling right now is user registration, not sure how to add data OAuth2 module while registering a user, could You write something about it?
File: /application/api/migrations/m150504_104847_create_products_table.php
Column name is type bigint or type text?
Hi, i was trying to set something like this
public function accessRules() { return [ [ 'allow' => true, 'actions' => [ 'index', 'view' ], 'roles' => ['@'], 'scopes' => ['default', 'admin'] ], ]; }
But, when i try to access with the eihter scope (default, admin) gime this error
{ "error": { "name": "Forbidden", "message": "You are not allowed to perform this action.", "code": 0, "status": 403, "type": "yii\\web\\ForbiddenHttpException" } }
When is only one scope all works fine.
It will be nice to explain this in readme as this is central to Authorization. Many of us comes thinking of RBAC which is actually not there
Hi, is it possible to authorize client app passing client id and client secret in request header? I do not want to retrieve access token by client credentials, but only protect my Rest API with client id and secret.
Hi @ikaras,
I am using yii2-advanced-template but implemented your logic for oauth2 scopes and permissions. I have created all the files like you and everything is working fine but i want to show "You need to login first" instead of "You are not authorized to perform this action" for requests without access token. As per Yii documentation after rest authentication you can grab the user identity from Yii::$app->user->identity but I am getting null even if the correct access token is passed.
After config the project. I test request public api point. It works. But when I test request to get token, it got
HTTP/1.1 400 Bad Request
Host: localhost:6666
Connection: close
X-Powered-By: PHP/5.6.8
Content-Type: application/json; charset=UTF-8
{"name":"Bad Request","message":"The grant type was not specified in the request","code":0,"status":400,"type":"yii\\web\\HttpException"}~/Code/PHP/yii2-oauth2-rest
[15:21:57]--->
About to try to add some additional roles (following the simpler approach to RB access mentioned in a few posts) So plan to override the already overridden AccessRules class to handle the additional roles and then update the controller rules for the specified roles. Have you any views on this approach?
Now, My purpose is api.test.com/book/v1 && api.test.com/music/v1 or api.test.com/v1/book/ && api.test.com//v1/music/ . But i do not know how to do , can you help me. Thanks.
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.
I did this quite easy with my own rest app. But here it is more difficult because the login does not have an email or password. So providing an alternative route for the login with another Auth service seems logical and I could generate the key and death counter by my own.
But this seems messy.
Do you have any better thought how to integrate it in your existing flow, so that this ecosystem is able to be connected by other ecosystems like FB or Twitter or what else?
Hi, I've just installed the template, but seems the yii2-oauth2-server was updated to latest (composer is marked as *) and broke compatibility with this application. What is the original version number? Thanks!
Readme seem outdated and missing some thing.
If you can get time to update it it will be great
Hi, I hope you can help me.
When I run the migration, the first one, I get an error 'Exception 'yii\db\Exception' with message 'SQLSTATE[HY000] [2002] Connection refused'
This is the command:
/Applications/MAMP/bin/php/php5.6.10/bin/php ./yii migrate --interactive=0
and this is the db config:
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;port:8889;dbname=asc_auth;unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock',
'username' => 'myuser',
'password' => 'mypassword',
'charset' => 'utf8',
],
Same error without the unix_socket part.
I checked with another Yii2 template that the db connection is working with that string.
Thank you
I execute the following commands:
curl -i -H "Accept:application/json" -H "Content-Type:application/json" -XPOST "http://127.0.0.1:9093/oauth2/token" -d {"grant_type":"password","username":"tgy3300","password":"123456","client_id":"testclient","client_secret":"testpass"}
Prompt:
<b>Deprecated</b>: Automatically populating $HTTP_RAW_POST_DATA is deprecated a nd will be removed in a future version. To avoid this warning set 'always_popula te_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in <b>Unknown</b> on line <b>0</b><br /> <b>Warning</b>: Cannot modify header information - headers already sent in <b>U nknown</b> on line <b>0</b><br /> {"name":"Bad Request","message":"The grant type was not specified in the request ","code":0,"status":400,"type":"filsh\\yii2\\oauth2server\\exceptions\\HttpExcep tion"}
Hi,
How to customize error messages/return?
I need to remove
"type":"yii\web\ForbiddenHttpException"
from status 403...
any idea?
thanks all.
Hi,
Thanks for your great effort. i am using your template for my api and have couple of doubts. Hope you help me clear those :
Thanks
After installation, when I try to reach application/api/www/index.php, I get an error 404.
What can I do to find out why? the file is there.
Thank you.
hi,Ihor.Glad to meet you, I'm a PHP rookie from China, see your ikaras/yii2-oauth2-rest-template project on GitHub, but I have installed the configuration, but still running is not correct. I would like to ask you a good configuration of the entire project demo can send me, thank you. My email [email protected]. thank you.
Hi there
Could you please shed any light on where I may be going wrong? Problem is that access restrictions are not functioning for the protected and custom scopes, so any call made returns data.
User table & oauth tables set up, populated and all working. Access Token requests for all scopes are working fine & the tables are updated too. My Controller has the same access rules as you have in ProductController.php e.g.
public $modelClass = '\api\common\models\Video';
public function accessRules()
{
return [
[
'allow' => true,
'roles' => ['?'],
],
[
'allow' => true,
'actions' => [
'view',
'create',
'update',
'delete'
],
'roles' => ['@'],
],
[
'allow' => true,
'actions' => ['custom'],
'roles' => ['@'],
'scopes' => ['custom'],
],
[
'allow' => true,
'actions' => ['protected'],
'roles' => ['@'],
'scopes' => ['protected'],
]
];
}
public function actionCustom()
{
return ['status' => 'ok', 'underScope' => 'custom'];
}
public function actionProtected()
{
return ['status' => 'ok', 'underScope' => 'protected'];
}
}
example of a call with protected Access Token:
http://localhost:8085/v2/videos/8?access_token=e78354aae150c3a75507c86de11610badd4ab74d
If I call http://localhost:8085/v2/videos/8/protected I get a Not Found (#404)
sample of the main.php
'controllerNamespace' => 'api\controllers',
'defaultRoute' => 'video',
'modules' => [
'v1' => [
'basePath' => '@app/modules/v1',
'class' => 'api\modules\v1\Module'
],
'v2' => [
'basePath' => '@app/modules/v2',
'class' => 'api\modules\v1\Module'
],
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'tokenParamName' => 'accessToken',
'tokenAccessLifetime' => 3600 * 24,
'storageMap' => [
'user_credentials' => 'api\models\User',
],
'grantTypes' => [
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials',
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true
]
]
],
],
'components' => [
'user' => [
'identityClass' => 'api\models\User',
'enableAutoLogin' => false,
'enableSession' => false
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
'POST /oauth2/<action:\w+>' => 'oauth2/default/<action>',
[
'class' => 'yii\rest\UrlRule',
'controller' => ['v1/video', 'v2/video'],
'extraPatterns' => [
'GET custom' => 'custom',
'GET protected' => 'protected',
],
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
],
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser'
],
'enableCookieValidation' => true,
'cookieValidationKey' => 'nnnnnnnnnn'
],
'response' => [
'class' => 'yii\web\Response',
'formatters' => [
yii\web\Response::FORMAT_HTML => '\api\components\HtmlResponseFormatter',
],
'on beforeSend' => function (\yii\base\Event $event) {
/** @var \yii\web\Response $response */
$response = $event->sender;
// catch situation, when a controller hasn't been loaded
// so no filter was loaded too. Need to understand in which format return result
if(empty(Yii::$app->controller)) {
$content_neg = new \yii\filters\ContentNegotiator();
$content_neg->response = $response;
$content_neg->formats = Yii::$app->params['formats'];
$content_neg->negotiate();
}
if ($response->data !== null && Yii::$app->request->get('suppress_response_code')) {
$response->data = [
'success' => $response->isSuccessful,
'data' => $response->data,
];
$response->statusCode = 200;
}
},
],
],
'params' => $params,
];
when request "oauth2/token" ,it responses "Client credentials were not found in the headers or body"
Since this acts as template, its good to explain how Access Control, specifically Scopes works and what to do If someone wants to use RBAC with your template
Hey, I've seen Your User::findIdentityByAccessToken(...) method and I don't think You should use the module like that, I mean, that code You call is already called before You enter findIdentityByAccessToken() method, so You are already authorized if You get there.
I've thought of using an activeRecord call to the model containing my token (I already have the token as a param) so my implementation of the method is like this:
use filsh\yii2\oauth2server\models\OauthAccessTokens;
public static function findIdentityByAccessToken($token, $type = null)
{
$oauthToken = OauthAccessTokens::findOne(['access_token' => $token]);
if ($oauthToken !== null) {
return static::findIdentity($oauthToken->user_id);
}
return null;
}
That gives me the userId I want and I don't have to repeat the whole authentication. I'm not really sure if that is the proper approach. For one I wouldn't want to access the model declared in a module explicitly. Sorry for the long rant ;)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.