ghan
ghan

Reputation: 565

How to secure API endpoints without user authentication

I am creating a SPA using angular2 & lumen 5.4. Lets just say there are two routes. One GET route that returns JSON data to display, and one POST route for uploading files to the database. Its an in-house app that will have no login (this is out of my hands).

How can I properly secure the endpoints? For the POST upload form I could include a hidden token but that isn't secure at all. All of the authentication tutorials for lumen involve user login which is not an option for me.

Any examples or tutorials would really help since I have always used user authentication in the past

Upvotes: 2

Views: 8072

Answers (2)

wujt
wujt

Reputation: 1328

You can use simple middleware and MySQL, e.g.:

<?php
namespace App\Http\Middleware; 

use App\ApiKey;
use Closure;

class ApiMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $tokenValid = ApiKey::where('api_key', $request->header('Authorization'))->exists();

        if (!$tokenValid) {
            return response()->json('Unauthorized', 401);
        } 

        return $next($request);
    }
}

API_KEY could be some random string, just use str_random(64); and save it to database. Then with every request you should attach this token as a Authorization header. Simple and secure.

At least but not last, don't forget to register it afterwards.

Upvotes: 7

bretanac93
bretanac93

Reputation: 627

You could use security based on IP address or something like that, but is the first time that I see something like your question, at any point of your app, if you want security, you need credentials, of course, you always can make other kind of auths, like enter the phone number or the email and I send you a token which you'll introduce in a further form, otherwise, I don't know what else to do in a situation like that.

Upvotes: 1

Related Questions