Please guide me about my Yii2 code about RESTFul authentication by token - rest

I have been look around google whole day and still not getting idea how to achieve RESTFul httpBasicAuth by using token.
First, I would like to ask can i using RESTFul HttpBasicAuth without Https ?
Then, below is my code to try to do Yii2 RESTFul HttpBasicAuth authenticaton, hope someone can spend some time review on my code and guide me what wrong on my code.
First this is my yii2 config setting about User Application component:
'user' => ['identityClass' => 'common\models\Users',
'enableAutoLogin' => false
],
then below is snippet of my common\models\Users IdentityClass
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\web\IdentityInterface;
use app\models\Ostoken;
class Users extends \yii\db\ActiveRecord implements IdentityInterface
{
public static function findIdentityByAccessToken($token, $type = null) {
/* Compulsory for RESTFul*/
// die("trying...");
// throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
file_put_contents("/var/www/html/y2api/logs/RESTFul_login_".date("Y-m-d"), date("H:i:s").":".$token."\r\n", FILE_APPEND);
$apiUser = Ostoken::find()
->where(['token' => $token])
->one();
return static::findOne(['username' => $apiUser->username]);
}
}
then I try to call the restful URL by http://192.168.33.10/api/Banktransactions?access-token=xxxxxxxx
then i get following error in json format :
{
"name": "Unauthorized",
"message": "Your request was made with invalid credentials.",
"code": 0,
"status": 401,
"type": "yii\\web\\UnauthorizedHttpException"
}
as you can see I put a file_put_contents in findIdentityByAccessToken but it never execute.

First question:
First, I would like to ask can i using RESTFul HttpBasicAuth without Https ?
Answer: You can, but:
Since an access token can be used to uniquely identify and authenticate a user, API requests should always be sent via HTTPS to prevent man-in-the-middle (MitM) attacks. (https://www.yiiframework.com/doc/guide/2.0/en/rest-authentication#authentication)
Second...question?:
I'm 100% sure this is because CORS.
Check out this:
https://www.yiiframework.com/doc/api/2.0/yii-filters-cors
Ever tried to reach the url through localhost? If so and it worked then you need to set up a CORS filter to be able to make a request to your server.

Related

How to make a call to Firestore using gRPC

I'm trying to build a gRPC client for Google's Firestore API in Elixir.
Before starting to write some code , I thought that it would be wise to first start with BloomRPC in order to debug the issue.
As base url, I'm using https://firestore.googleapis.com where I pinned the rot certificate.
As auth I'm using an access_token obtained using oauth with the following 2 scopes: "https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore"
being passed as a Authorization header:
{
"Authorization": "Bearer 29ya.a0AfH6SMBDYZPsVgQv0PMqyGRXypc3DfWF_2jbvAJKMquTaryCvxEB7X1Rbprfk1Ebrwid2bXbcR3Aw-d1Tytlo_lThkyqRDRIbnSz5-nQ3xWklkmjyFMAuQtFCoz01hk3vbgBwd2gdbFNNWiOU_8NqPC_vElyz2-cQ34"
}
And I get back:
{
"error": "3 INVALID_ARGUMENT: Missing required project ID."
}
So clearly I should be passing the project ID somehow but I can't find it anywhere in the docs. Anybody any clues?
I just figured out what I was doing wrong.
Basically the Bearer token I was using is correct (obtained via the OAuth Playground).
The trick was to specify the PROJECT_ID in the parent parameter of the request:
{
"parent": "projects/[project-id]/databases/(default)/documents",
"page_size": 10
}
I should have just read the docs properly :)

Correct uri for DeleteAgentUser (Google Homegraph)

I'm trying to use the DeleteAgentUser of Homegraph to unlink a user with Google. I already implemented the ReportState and the correct uri for this is: https://homegraph.googleapis.com/v1/devices:reportStateAndNotification. So I thought the DeleteAgentUser has to be: https://homegraph.googleapis.com/v1/devices:deleteAgentUser but I'm getting a '404 Not Found' Error.
I tried it with:
https://homegraph.googleapis.com/v1/devices:deleteAgentUser
https://homegraph.googleapis.com/v1/deleteAgentUser
https://homegraph.googleapis.com/v1/devices:DeleteAgentUser
https://homegraph.googleapis.com/v1/DeleteAgentUser
everything with post and delete request and always getting the error.
What is the correct Homegraph uri to delete a user from Google?
Looking at the RPC defined in the public protobuf, it seems that the implementation is defined as:
rpc DeleteAgentUser(DeleteAgentUserRequest) returns (google.protobuf.Empty) {
option (google.api.http) = {
delete: "/v1/{agent_user_id=agentUsers/**}"
};
}
So, it seems like you'd send a DELETE request to https://homegraph.googleapis.com/v1/{agent_user_id} or maybe https://homegraph.googleapis.com/v1/agentUsers/{agent_user_id} with your agent user id, and signed with your authorization token similar to Report state.

make meteor restful api/web-service

I have created a new url/route in my app where I need to write a web-service. I need to write a service that deletes user according to the parameters passed in the service. For now, anyone should be able to call that service (will make it secure at later stage). App is built on meteor.
My url is : loaclhost:3000/deleteUser. Now one should be able to call my delete user function defined on this page and pass json structure data as an argument to it. If the data is valid, then the user should be deleted.
Using simple:rest package
Meteor.publish("delUser", function (a, b) {
UserDetails.remove({}); //delete user according to data received
}, {
url: "/testing/delUser", //url where third party will call the function
getArgsFromRequest: function (request) {
// Let's say we want this function to accept a form-encoded request
// with fields named `a` and `b`.
console.log('received : ' + JSON.stringify(request.body) );
var content = request.body;
// Since form enconding doesn't distinguish numbers and strings, we need
// to parse it manually
return [content.a, content.b];
}
})
How to access the function, delUser from a thrid party? I also need to add authentication at a later stage.
Personnally, I use this :
simple:rest
simple:json-routes
simple:rest-accounts-password
I find it easier to implement.
even iron:router comes with server side routes where you can build your own functions and api calls.
http://iron-meteor.github.io/iron-router/#restful-routes
Sample (Server side code) :
Router.map(function () {
this.route("api", {path: "/api/:paramsYouNeed",
where: "server",
action: function(){
this.response.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
if (this.request.method == 'POST') {
var response;
//do whatever you want to do
this.response.end(response);
}
}
});
The other user can call this by making a http.post request to the above url (http:www.a****a.com/api/params)
The easiest way to do this is use the restivus package.
https://atmospherejs.com/nimble/restivus
Restivus makes building REST APIs in Meteor 0.9.0+ easier than ever
before! The package is inspired by RestStop2 and Collection API, and
is built on top of Simple JSON Routes to provide:
A simple interface for creating REST APIs
Easy setup of CRUD endpoints for Mongo Collections
User authentication via the API
Optional login and logout endpoints
Access to this.user in authenticated endpoints
Custom authentication if needed
Role permissions for limiting access to specific endpoints
Works alongside the alanning:roles package - Meteor's accepted role permission package

REST: Update resource with unknown (server-generated) value

I have a resource foo with the following structure:
GET /foo/1 returns:
{
"id": 1,
"server-key": "abcdef",
"status": "expired"
}
Status can either be active or expired. If it is expired I want the server to generate a new one.
Normally I'd issue PUT/PATCH foo/1 with the new key, but client doesn't know the key-generation algorithm.
I could also do a POST foo/1/server-key with no body, but that feels strange (I know this isn't very scientific reason though).
Any good ideas/patterns?
In case when you've got expired entity just make POST call on /foo without any parameters and server should return new entity (and HTTP response code should be 201):
{
"id": 2,
"server-key": "xyz",
"status": "active"
}
If some resourece is expired it is unconvinient to make it active again by PUT/PATCH request.
The approach I would adopt is to set a null value to server-key and let the server deal with it, but I do that because it's a consistent behavior in my APIs for the server to fill missing values with defaults.
Other than that, a simple POST to the URI as suggested in the other answer is adequate.
I think that you should use a PUT/PATCH method in your case to ask for generate a token if expired. Generally it's not really RESTful to put an action name within the resource path ;-)
I would see something like that:
Get the element: GET /foo/1
If the status is expired, ask for a new server key to be generated: POST /foo/1. In this case, this method will be used to execute an action to reinitialize the key on the server side
Using the method PUT corresponds to update the complete representation with a new one provided by the client. With the method PATCH, you will do a partial update of the representation.
Here is a link that could give you some hints about the way to design a Web API (RESTful service): https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
Hope it helps you,
Thierry

OAuth & facebook access_token not working, need OAuth expert

I have read the 1000+ blogs about how the redirect_uri has to be the same in both calls to OAuth in order to get a user token, but 100% of the time, regardless of how I format the URL, it fails with:
{
"error": {
"message": "Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request",
"type": "OAuthException",
"code": 100
}
}
I have been meticulous in making sure that the URLs in both calls were the exact same. My URL has to have a ? in it and I have tried replacing it with %3f but that didn't help. There has to be something else that can cause this error, I need to learn what that might be?
This seemed to break for me over the past month sometime. We did a show in late July and things worked fine (had a different base URL for that show since it was a different server). Could it be that the URL is of this format:
someprestuff.morestuff.mainurl.com?prm=value
Are there too many "parts" to the URL for Facebook to accept it?
I'm looking for alternate things to look for.
The url should be the same and it has to be escaped. In the url it has to look like this:
http%3A//someprestuff.morestuff.mainurl.com%3Fprm%3Dvalue
Jim's comment above worked, but to clarify, it was a forward slash that fixed it for us.
Had the same problem today, the problem turned out to be that the redirect_uri used a http:// URL Schema, and Facebook only accepts https://
I just finished tracing this issue on a server that was behind a load balancer. It turns out that while the load balancer was passing the HTTP_X_FORWARDED_PROTO header, somehow between the V3 PHP Facebook library, PHP and Apache, the header was not being recognized.
Here is the relevant code from the library:
protected function getHttpProtocol() {
if ($this->trustForwarded && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
return 'https';
}
return 'http';
}
/*apache + variants specific way of checking for https*/
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] == 1)) {
return 'https';
}
/*nginx way of checking for https*/
if (isset($_SERVER['SERVER_PORT']) &&
($_SERVER['SERVER_PORT'] === '443')) {
return 'https';
}
return 'http';
}
As you can see, there are a few scenarios being accommodated here, so you'll have to ensure that whatever situation applies to you is properly configured for this block of code to succeed.
The most likely solution will be to set trustForwarded to true in your facebook config array.