Search code examples
djangodjango-rest-frameworktwo-factor-authenticationtotpdjango-two-factor-auth

Django Two Factor Auth combined with Rest Framework?


I'm trying to implement django two factor auth into my Rest API. Is there a possibility to implement this by using custom views and model creations? Because, at least that's the way I understood it, this library is mainly working based on default django templates and predefined routes. Is it possible to combine this library with a Rest API or should I use another library?


Solution

  • You cam use pyotp library. It's compatible with most of the two factor authenticator app like google authenticator. Very easy to use.

    Here is an example how to use use:

    base32 = pyotp.random_base32() 
    >>> base32
    'ERAAADLXLDFBVL2JSR4RLR73DWFWYSTU'
    >>> totp = pyotp.TOTP(base32)
    >>> totp.now() 
    '206328'
    

    It will generate random code after every 30 seconds. For generate provisioning URIs for use with the QR Code scanner:

    pyotp.totp.TOTP('ERAAADLXLDFBVL2JSR4RLR73DWFWYSTU').provisioning_uri(name='[email protected]', issuer_name='Secure App')
    >>> 'otpauth://totp/Secure%20App:alice%40google.com?secret=ERAAADLXLDFBVL2JSR4RLR73DWFWYSTU&issuer=Secure%20App'