Laravel OAuth token for one user only - php

I am creating a Web App where I need to access an API from Mobile Apps. I have implemented some Public API methods, which are fine and work great.
Now, I am working on the restricted API methods i.e. updating User info etc.
I have started implementing the OAuth server package lucadegasperi/oauth2-server-laravel
It is all setup and dishing out tokens no problem, using the documentation from the GitHub repo and this tutorial.
I can get an OAuth token using a POST call to my public API method oauth/access_token, this returns an Access Token no problem.
Now, my issue is:
Once I have the Access Token, how do I know who it was issued to and what they have access to? There is no user_id associated with this token.
Can I simply create a column in the table and use Eloquent models to find out and how would I associate this token with a user?

Ok, so after scouring the Source Code and documentation many times I gave up and posted a question here. I then thought "one more time". I found this gem.
And right down the bottom (not in TOC or anything) is:
Finding access token owner
use LucaDegasperi\OAuth2Server\Facades\Authorizer;
Authorizer::getResourceOwnerId();
Pair this with:
$user = User::find($user_id);
Like so:
Route::get('protected', ['middleware' => 'oauth', function() {
$user_id = Authorizer::getResourceOwnerId();
$user = \App\User::find($user_id);
return $user;
}]);
And Bob's your uncle. We have who made the request.

Related

Laravel Api Token

I have read some tutorials and video tutorials and they explain how to create a api_token.
I know that I have to change the AuthController and I have to add a new field which it is api_token when a new user registers. I know that I have to add auth middleware in the routes, etc.
But what I dont understand is this...
1) A new user registers in the app.
2) The app create to the user an api_token automaticly.
but I wonder how this user will know which it is its api token because if this user turns off the computer and then it returns to the app how will this user know what it is its api token again? because he will not register again.
Thanks.
Have a look at Laravel Passport. Laravel Passport uses for instance an OAuth autherization. If you log in your application you get an access token and a refresh token. The access token is self explaining you basically get access to the application, the refresh token does refresh you access after a specific amount of time that value is typically written in a configuration file.

how to convert my laravel project to an api?

I have a laravel project, which is about Students and their courses.
This project has CRUD functions, where the user(mainly the school's admin) can create users and assign their courses. I have successfully created this project.
But now how do I make this an API?. I need to share the students courses to another website, therefore I need to create an API right?
I have never created an API in laravel, when I checked the documentation of Laravel, it has this topic called API authentication using passport, is this talking about requiring users to login first before accessing the API
?.
Would be very helpful if someone can explain a little bit about creating an API and where to start from.
You are trying to give another website access to view the students courses. Is the data publicly available ? If yes, you don't need Authentication. But that means literally everybody with the API URL can access the data. Using Authentication on your API is entirely up to you.
Now, to create an API, it's very easy with Laravel. There are tons of free resources online like this one: https://tutorials.kode-blog.com/laravel-5-rest-api. Just google the topic for more.
Basically, the API works exactly like what you did in terms of controller and routing. In laravel 5.4, there is a separate route file for api located in routes/api.php. That's where you define your routes.
Route::get('courses', 'Api\CourseController#index');
This route will respond to https://www.website.com/api/courses and will link to the function index() located in app/Http/Controllers/Api/CourseController.php. You will have to create that controller yourself.
Looking at that route file, you can see something out of the box
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
It means the route /api/user will require authentication because of the auth:api middleware.
In your controllers so far, you return views. In api controller you will return response
public function index()
{
$courses = Course::all();
return response()->json($courses);
}
The application calling the website will receive a JSON object containing an array of courses. More about responses here: https://laravel.com/docs/5.4/responses
About api_token
The default API authentication offered by laravel works by checking api_token attribute from the users table. That api_token has to been present in the headers of the request sent to the api. Laravel will then use that api_token to identify the user making the request. In default application, to get a user, you do
$user = Auth::user();
Within your API controllers, you do
$user = Auth::guard('api')->user();
//Auth will look for api_token to get the user making the request

laravel 4.2 oauth complications

I have written an api for a project that uses, oauth2 to authenticate users, and lock down that api to only people with an access token, and it works fantastically well, we have a route group that looks like this,
Route::group(array('prefix' => 'api', 'before' => 'oauth'), function() {
});
The problem I am now facing is that scope of the project has changed and we need to extend the api a little bit. Basically at the moment, the API is used to create projects, and a project a can have a team that can CRUD a project.
The scope has changed now so that a project can also have client user who can follow a unique link to monitor the progress of the project, and update certain aspects of the project.
The problems are 2 fold,
1) You cant do anything on our API without an access token, so even a GET request for data to build the page would be turned down for a client user.
2) To get a access token you need a username and password. The key thing for a client user is that do not need to login, they should be able to just get a unique URL in email, and then load the project.
I figure that creating a custom grant type would be the best solution is that correct? If that is correct does anyone have any guidance on creating one?
If that is not the best way what other options do I have available to me?

Using google account for private website access

Currently, the person I'm developing for uses google docs to display the website/files. Which can only be accessed via google accounts ending in a certain domain name. For example danny#webtest.com if it's a webtest google account then it can access it.
Now I'm creating them a website not linked to google. However, I still need this authentication process.
Step One
login page will be a simple "connect with google account"
Step Two
user is redirected to login to google, if they're already logged in then moves to next step.
Step three email address is crosschecked with my database, if there a session is made for the row id of that user, if not then it is added.
I'm trying to keep this as simple as possible, however I have no idea where or how to do step Two.
After reading the Wikipedia introduction mentioned by #Izzy, you can have a look at google's Oauth2 introduction and then jump into google's quick start sample app; it gives a fully working commented php app of using oauth 2.0 to authenticate with a google account and fetch user data.
The code in the example uses the package google-api-php-client as well as a js library to reduce the boilerplate to simpler API calls. For the client/frontend side, javascript calls such as:
auth2.signIn().then(function(googleUser) {
onSignInCallback(googleUser.getAuthResponse());
}, function(error) {
alert(JSON.stringify(error, undefined, 2));
});
And on the server, php side:
$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// You can read the Google user ID in the ID token.
// "sub" represents the ID token subscriber which in our case
// is the user ID. This sample does not use the user ID.
$attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)
->getAttributes();
$gplus_id = $attributes["payload"]["sub"];
// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Successfully connected with token: ' . print_r($token, true);
Please note that requesting an email address will require asking further the permission (named Authorization scopes) from the client, as seen in this SO question:
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
You can then use any number of APIs that expose userinfo.email. One of these, Google_Service_Oauth2, has the helpful public method userinfo
$oauth2Service = new Google_Service_Oauth2(...);
$userinfo = $oauth2Service->userinfo;
Use OAuth2. Google uses it for authentication process.
OAuth states for Open Authorization. OAuth is protocol which is designed to work with HTTP enabling access tokens to be issues to third-party clients by auth server, with approval action from user.
OAuth is starting to be deprecated, and all major companies are starting to use OAuth2 protocol which is improved version of OAuth, but unfortunately it is not backward compatible.
You can find several implementation in PHP like this one.

Code Igniter - Consuming my own API and authorisation

I am attempting to build my HMVC codeigniter install into an API centric HMVC (yeah I know!)
I have ion_auth as the authorisation system at the moment.
The way I have it set-up is
MODELS
CONTROLLERS
- API CONTROLLER
- CONTROLLER
VIEWS
With the API controller accepting JSON encoded inputs and sending JSON encoded outputs.
Now - it all works fine -> I can access the API by calling controller/api and can pass it JSON and receive JSON back.
I then just call the controller/api from within my normal controller
My problem now comes with authorisation.
Nobody can access the API if they aren't logged in through Ion_auth (so it is secure) BUT
How do I then expose the API?
I presume I need to go down the O Auth route but I have tied myself in a knot trying to get my head around how I can use O Auth for the API and not impact the performance of my application when accessed via my controller.
It is down to not understanding how O Auth works fully (I can implement it and understand the hand-shakes etc. but the nitty gritty) -> if I found some way of authenticating a user via O Auth (I mean a site user not an API user) how does this carry through to my controllers - is it stored in a session? Can I give my controllers Authorisations? (Do I need to)
OR - is there a way of doing this with Ion Auth that I haven't heard about?
FOR CLARITY
I want my own application to be able to use it's own API, but do not know how to set up the authrosiation so the API can be consumed directly as well as locally by the application itself (when users are using the site)
HELP!!!!
Thanks in advance!
Maybe you can remove O auth for the API and just create a table of access key. When someone calls the API he needs a key that registered in the table. No ?
Using Promo's answer, plus a little thought after he pointed out the obvious all I did was this:
public function __construct()
{
parent::__construct();
//see if they logged in -> if they are no problem as they are obviously using the page through my application, if they aren't then we do checks for the API
if (!$this->authentication->logged_in())
{
$this->token = $this->input->get_post('token');
//API should have a token set before anything can happen, this is for every request
if($this->token){
//Check that the token is valid
if (!$this->checkToken($this->token)){
$this->error('Token did not match');
}
//all clear if we get to here - token matched
}else{ //no token was found
$this->error('No Token was sent');
}
}
}

Categories