phpioslaraveloauth

Logging in users with API built in laravel


I am building my first rest API for an iOS app. The framework I use for buidling the API is Laravel.

Everything works great so far but I am not sure on how to log users in using the API. Could sessions work here? Im already using SSL/HTTPS but I dont wanna authenticate users on each request, so whats the best way to only make them log in once?

Also, should oAuth work fine here?

If you have any examples on how to log users in on a Laravel built API please share.


Solution

  • With my experience, Laravel built in Authentication component is just be able to applied to normal authentication via form, session and cookie. To handled API authentication, I have used these methods, hope that one of them is suitable for you.

    OAuth 2

    With the help of lucadegasperi/oauth2-server-laravel, you can make your API secured via OAuth flows. More documentation can be found at the package wiki on Github or the PHP League Oauth2 home page. You can use filters to secure your API routes as follow:

    Route::get('protected-resource', ['before' => 'oauth:scope1,scope2', function() {
        // return the protected resource
    }]);
    

    However, OAuth need a database to save client credentials and some more settings, if your API is not so complicated, this solution may not suitable.

    HTTP Authentication

    This solution is more simple than OAuth and I recommend using it with an SSL (HTTPS) connection because the authentication information can be visible why using this. The packages I used before is Intervention/httpauth. You have two options with authentication method by using this package: basic (send a base64 encoded of the combination username:password via HTTP header) or digest (use MD5 algorithm to encode your information before sending via HTTP header). This solution does not required any database.