Home > front end >  Authenticate User across 2 different Rails apps with Devise
Authenticate User across 2 different Rails apps with Devise

Time:10-08

I have two Rails apps that share a database and use Devise for authentication. One of them is purely an API. I want to be able to make a request from one app to the other (API) and be able to authenticate the User.

I've tried using JWT but the signature keeps getting flagged. I could just pass the encrypted_password but I don't know how to validate it on the other app.

I feel like I'm missing something simple.

CodePudding user response:

If the db is shared among apps you can simply authenticate the user via Devise :database_authenticatable on the api-only app. But why are you sharing the same db with 2 apps?

You could use Devise-Jwt gem to generate a JWT on the 1st app, then pass it with every request to 2nd app and validate it. Obviously the encryption key for the JWT must be the same on both apps.

CodePudding user response:

I ended up solving this using the following solution. I understand this may not be recommended or extremely secure, but for my needs and the downstream impact it works just fine:

I generate the encrypted information in App 1 and then send an HTTP request to App 2 and decrypt it on that end.

App 1:

def generate_encryption
    pass_phrase = ENV['SHARED_SECRET']
    salt = '8 octets'
    encryptor = OpenSSL::Cipher.new 'AES-128-CBC'
    encryptor.encrypt
    encryptor.pkcs5_keyivgen pass_phrase, salt
    encrypted = encryptor.update @user.email
    encrypted << encryptor.final

    return encrypted
end

App 2 (API):

def decode_encryption(encrypted)
    pass_phrase = ENV['SHARED_SECRET']
    salt = '8 octets'
    decryptor = OpenSSL::Cipher.new 'AES-128-CBC'
    decryptor.decrypt
    decryptor.pkcs5_keyivgen pass_phrase, salt
    plain = decryptor.update encrypted
    plain << decryptor.final

    return plain
end

I then use the decrypted message to locate a User and ensure they exist.

  • Related