Search code examples
laravelapisessiontddone-time-password

What is the recommended way to handle one-time-password when using APIs for authentication?


I am using TDD to implement APIs for an authentication system in Laravel. This system uses the one-time-password (OTP) method for authentication. In the first step, an OTP token is issued for the user and stored in the session. In the second step, the server receives a request containing an OTP token from the user and checks if the received OTP token is identical to the one stored in the session.

I have written a test for a scenario where the user sends an invalid OTP token to the server, but I don't have access to the server session in the test, so I cannot compare the invalid token against the session value.

Is there a better way than using sessions to implement this? Is there a solution to access the server session in the test?

Thank you all.


Solution

  • Database

    Add a column to the users table for OTP

    Step 1:

    • generate OTP and issue to the customer
    • Store OTP in database

    Step 2:

    • Server receives request from user with OTP
    • compare against value in database and delete from database

    Pros: Simple to setup

    Cons: Additional database queries and need to remember to delete it even if after issuing OTP to user request from user is never made

    Cache

    Step 1:

    • Generate and issue OTP to user
    • Store OTP in Cache
    Cache::put("otp-{$user->id}", OTP, now()->addMinutes(5));
    

    Step 2:

    • Server receives request from user with

    • Check against the value in cache

    Pros: Simple to setup and OTP can be destroyed automatically

    Cons: Cache management becomes vital area of application