I want to create web services with laravel but i don't do this.
I use routes some one like this:
Route::group(array('prefix' => 'api/v1', 'before' => 'basic.outh'), function(){
Route::resource('url', 'UrlController#index');
Route::resource('show', 'UrlController#show');
Route::resource('destroy', 'UrlController#destroy');
});
But this Route filter just want to username, like this:
Route::filter('auth.basic', function()
{
return Auth::basic("username");
});
I want to be make my system like Codeigniter RESTful api. This is possible?
Could you suggest me any examples?
Yes, definitely possible.
Personally, i would recommend using OAuth2 for token based authentication, which is better suited for APIs. OAuth has a fairly steep learning curve, but luckily, there is a package for Laravel (an OAuth2 wrapper) that makes it pretty easy, as it will generate and validate the tokens for you.
Package:
https://github.com/lucadegasperi/oauth2-server-laravel
Example:
I have a setup similar to this. The code below isn't meant to replace going through the documentation, but this is something like what your routes would look like using this wrapper.
Route::group(['prefix' => 'api/v1', 'before' => 'apiErrors'], function()
{
// Returns a valid token based on grant_type and credentials when a request is made to the accessToken endpoint.
// I use 'client_credentials' and 'refresh_token' for APIs serving mobile apps, for example. You can use that, or roll your own.
Route::post('accessToken', function()
{
return AuthorizationServer::performAccessTokenFlow();
});
// 'oauth' filter makes sure there is a valid token present
Route::group(['before' => 'oauth'], function()
{
// Your protected endpoints
Route::resource('url', 'UrlController#index');
Route::resource('show', 'UrlController#show');
Route::resource('destroy', 'UrlController#destroy');
});
});
Related
When user enter username and password on the the browser and successfully logged in.
I like to make some API requests after user have logged in.
Laravel 5.3 provide api.php in routes folder.
in api.php I have included:
Route::group(['middleware' => ['auth']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
When requesting domain.com/api/test on the browser, for some reason it is redirecting to /home?
API token is not needed.
If you are specifying routes in api.php, you will need to use the auth:api middleware. So using your example it would be:
Route::group(['middleware' => ['auth:api']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
Notes about Token auth and Laravel 5.3:
If you've setup laravel's default auth system, you will also need to add a column for api_token to the user table. If you are using DB seeders, you might want to add something like:
$table->char('api_token', 60)->nullable();
to your users table seeder. Alternatively just add the column manually and fill that column with a random 60-char key.
When making the request, you can add the api_token as a URL/Querystring parameter like so:
domain.com/api/test?api_token=[your 60 char key].
You can also send the key as a header (if using Postman or similar), i.e:
Header: Authorization, Value: Bearer [your 60 char key].
I order to get a useful error if the token is incorrect, and not just be redirected to login, also send the following header with all requests:
Header: Accept, Value: application/json. This allows the expectsJson() check in the unauthenticated() function inside App/Exceptions/Handler.php to work correctly.
I found it hard to find clear docs from Laravel about using token auth with 5.3, I think it's because there's a drive to make use of Passport, and it supports tokens in a different way. Here's the article that probably helped most getting it working: https://gistlog.co/JacobBennett/090369fbab0b31130b51
first install the passport as stated here laravel passport installation
while consuming your own api add below line in your config/app.php in middleware section
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
now change your route to
Route::group(['middleware' => ['auth:api']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
now in your config/auth.php change these lines
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
The reason you are being redirected back to home is because the auth middleware checks if a user session is stored in your browser, but since api middleware does not make use of sessions (see app\http\kernel.php), your request is considered unauthenticated
If you would like to perform simple APIs that utilize sessions, feel free to add them in your web routes, and make sure to secure them by grouping them inside an auth middleware.
The standard behaviour in Laravel 5.5 is to delegate handling of authentication exceptions to app/Handler::unauthenticated(), in your project's application code. You'll find the code in there that redirects to the login page, and you can override it or perform further tests and contextualization in there. In previous versions of Laravel, 5.3 among them I believe, this exception handling was executed way down within the Laravel library within the vendor folder.
I'm up and running with Laravel Spark, but I'd like to pull some of the user auth methods (and later, some others) in to my API.
Spark's default registration method is a POST request to /register that calls Auth\RegisterController#register.
I would like registration to be POST request to api/v1/register but for the sake of simplicity, I'd like to simply call Spark's Auth\RegisterController#register method.
I did try simply copying the RegisterController from Spark in to my app's controller directory, but that didn't seem like an elegant solution and it didn't work anyway.
My app\Http\api.php contains the following group:
Route::group([
'prefix' => 'api/v1',
'middleware' => 'auth:api'
], function () {
Route::get('register', 'Auth\RegisterController#showRegistrationForm');
Route::post('register', 'Auth\RegisterController#register');
});
I'd love input and advice on the best way to pull in some of those Spark methods that I get out of the box.
Thanks in advance!
I'm using the tymon/jwt-auth package for authentication an api with Laravel. It's working quite well and I have everything working properly.
However I'm unsure how to setup the jwt.refresh token middleware. I'm under the assumption that it will "auto-refresh" the token when expired?
I've add both to my middleware but can't seem to make it work.
Route::group([
'prefix' => 'api/v1',
'namespace' => 'Api\v1',
'middleware' => ['jwt.auth', 'jwt.refresh']
], function ($app) {
// Routes here
});
Perhaps I'm not sure how it works exactly, do I need to do polling for a some refresh end point. I kind of thought that was what the middleware was supposed to do automatically per request?
If you use the jwt.refresh middleware, the token is refreshed on every request. It's returned as a header on the response, so you need to take that header and store the new token on every request.
The returned Authorization header will be of the form Token: xxxxxxxxx
I am working on a project on laravel 5.1, and i want to make it as a RESTFUL api so later we can use the same code and request data from mobile apps or other websites. The project is in its initial stages and i want to make it correct right from the beginning.
Suppose i have a simple route which is calling a the dashboard method on the AdminController. So after logging in it redirects the admin to the dashboard page with some data.
/******************** Laravel Project ***********************/
//Routes.php
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', 'AdminController#dashboard');
});
// AdminController
public function index(){
$data = 'Some Data';
return view( 'superadmin.dashboard')->with('data', $data );
}
Now i want to get the same data in a wordpress project. How will i use this api to just fetch the data variable (without the view) ? I dont want to create another method for that, is there any way i can use the same function to fetch data as a json?
I read in another forum that we can access all the data as a REST like this. But this is not working.
http://admin:admin123#example.dev/dashboard
As always appreciate your help :)
Personally, I would create an application that is the API. In your case this is your Laravel application.
Then I'd make HTTP requests to the API from Wordpress, or a mobile application.
I find returning JSON from the API is easier to work with. Laravel makes this easy:
return Response::json(array(
'username' => 'superadmin',
'role' => 'admin',
'friends' => array(
'2345',
'884'
)
));
Also, don't send your username and password like that. HTTP auth is insecure. http://adrianotto.com/2013/02/why-http-basic-auth-is-bad/
I tend to use OAuth to secure my APIs.
I'm building a Laravel API which authenticates users using an authentication token. For any routes that need authentication, I'm wrapping them in an auth filter:
Route::group(array('before' => 'auth'), function() {
Route::get('user/account', 'UserController#getAccountDetails');
});
My auth filter basically decrypts the passed in authentication token and checks if it's valid:
Route::filter('auth', function()
{
// Try catch because Crypt::decrypt throws an exception if it's not a valid string to decrypt
try {
$authToken = Crypt::decrypt(Request::header('Authorization'));
// If there's a user tied to this auth token, it's valid
$user = AuthToken::where('token', '=', $authToken)->first()->user()->first();
if (!$user) {
throw new \Exception();
}
// Make the user globally accessible in controllers
} catch (\Exception $e) {
return Response::json([
'data' => [
'error' => 'You must be logged in to access this resource.'
],
'success' => false,
'status' => 403
], 403);
}
});
Pretty simple stuff, but I'm stuck on the next part. I want to be able to easily retrieve the current user record in my controllers and models.
For example, if I used Laravel's Auth library I could get the current user by doing Auth::user() in my controllers. I'd like to have that kind of functionality but I'm not sure how to build it. Could I write a class that gets instantiated after authentication with a static method that returns a User model?
Not sure if that's an option for you, but maybe you would like to use oauth2 instead of writing "your own" token based authentication?
There is quite nice ouath2 server wrapper for laravel project: oauth2-server-laravel.
According to it's documentation you can (for example for password flow authentication) put this in it's config:
'password' => array(
'class' => 'League\OAuth2\Server\Grant\Password',
'access_token_ttl' => 604800,
'callback' => function($username, $password){
$credentials = array(
'email' => $username,
'password' => $password,
);
$valid = Auth::validate($credentials);
if (!$valid) {
return false;
}
return Auth::getProvider()->retrieveByCredentials($credentials)->id;
}
)
And than you can you can authenticate (via username and password in that case) sending post request like that:
POST https://www.example.com/oauth/access_token?
grant_type=password&
client_id=the_client_id&
client_secret=the_client_secret&
username=the_username&
password=the_password&
scope=scope1,scope2&
state=123456789
Request will return generated token, and then you can make api calls as usual, just putting the token in the post data.
In your api logic getting the user by token is quite simple in that case, just run:
User::find(ResourceServer::getOwnerId());
It will makes stuff like: refresh tokens, other grant flows, scope access, clients management a lot easier. Out of the box in fact.
You can also secure any particular route like that:
Route::get('secure-route', array('before' => 'oauth', function(){
return "oauth secured route";
}));
You can find more details in oauth2-server-laravel documentation: https://github.com/lucadegasperi/oauth2-server-laravel
And oauth2 documentation: http://oauth.net/documentation/
It is true that the Auth::user() method is quite convenient. So, why not simply extend the Auth class to write your own authentication driver ? You can find all needed doc here.
You can then just use the Auth facade just like in every other laravel app you could write… wonderful, isn't it ?