Last active
          June 19, 2018 06:09 
        
      - 
      
- 
        Save matiaskorhonen/8fbe8978f1816e607547e05c52310003 to your computer and use it in GitHub Desktop. 
    Example AuthenticationToken implementation using ActiveSupport::MessageEncryptor
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | class AuthenticationToken | |
| # Encode a hash | |
| def self.encode(payload, ttl: 14.days.to_i) | |
| keygen = ActiveSupport::KeyGenerator.new(Rails.application.secrets.token_secret) | |
| key = keygen.generate_key(Rails.application.secrets.token_salt, 32) | |
| crypt = ActiveSupport::MessageEncryptor.new(key) | |
| payload[:expires] = ttl.seconds.from_now.to_i | |
| crypt.encrypt_and_sign(JSON.dump(payload.deep_stringify_keys)) | |
| end | |
| # Decode a token and return the payload inside | |
| def self.decode(token) | |
| keygen = ActiveSupport::KeyGenerator.new(Rails.application.secrets.token_secret) | |
| key = keygen.generate_key(Rails.application.secrets.token_salt, 32) | |
| crypt = ActiveSupport::MessageEncryptor.new(key) | |
| decoded = crypt.decrypt_and_verify(token) | |
| payload = JSON.parse(decoded) | |
| if payload["expires"] < Time.now.to_i | |
| raise TokenExpiredError.new("The access token has expired") | |
| end | |
| HashWithIndifferentAccess.new(payload) | |
| end | |
| class TokenExpiredError < StandardError; end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment