Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Google Sign In with OpenID

REST api Add authentication

edited September 2012 in Framework

In the docs it states: "You can use your handler to add things like authentication to your new API." I was wondering if there was a code example for how I might do this.

Comments

  • To use cookie-based authentication against Elefant's user table, you can use:

    <?php
    
    if (! User::require_login()) {
        // Unauthorized handling goes here...
        die ('You must be logged in');
    }
    
    $this->restful (new myapp\MyAPI ());
    
    ?>
    

    For a more API-oriented option, here's how you can add HMAC authentication:

    <?php
    
    // from apps/user/lib/Auth/HMAC.php:
    $this->require_auth (user\Auth\HMAC::init ($this, $cache, 3600));
    
    $this->restful (new myapp\MyAPI ());
    
    ?>
    

    From here, you need to generate API keys and tokens via Api::create_token():

    <?php
    
    list ($token, $api_key) = Api::create_token ($user_id);
    
    ?>
    

    The generated API key and token are automatically saved to the database, so the returned values are good to go.

    On the client-side, you'll also need to generate a token value for each request. This can be done like this (in PHP at least):

    <?php
    
    // Store these somewhere secret
    $api_key = '********';
    $token = '********';
    
    // The current API request info
    $request_method = 'POST';
    $host_name = 'www.example.com';
    $request_uri = '/your/api';
    $post_data = 'name=Joe&email=joe@example.com';
    
    // Build the data value from the current API request
    $data = $request_method . $host_name . $request_uri . $post_data;
    
    // Calculate the HMAC hash for the request
    $hmac = hash_hmac ('sha256', $data, $api_key);
    
    ?>
    

    When you make the API request, use HTTP Basic authentication and send the $token as the username and $hmac as the password.

    The nice thing about HMAC is it verifies the API key matches on both ends without actually sending it, since it's used to hash the data of the current request. This is the same technique services like AWS are using.

    Hope that helps!

  • Wow, this is great thanks a lot.

Sign In or Register to comment.