Skip to content

Instantly share code, notes, and snippets.

@keighl
Created December 19, 2012 13:37
Show Gist options
  • Save keighl/4336694 to your computer and use it in GitHub Desktop.
Save keighl/4336694 to your computer and use it in GitHub Desktop.
Secure API Request From iOS to Rails
class Api::V1::ApiController < ApplicationController
before_filter :token_authenticate
respond_to :json
def widgets
@widgets = Widget.all
end
private
def token_authenticate
unless params[:auth_token].present? and params[:auth_signature].present?
api_not_authenticated
return
end
user = User.find_by_auth_token(params[:auth_token])
if user.nil?
api_not_authenticated
return
else
hash = OpenSSL::HMAC.digest('sha256', params[:auth_token], AUTH_PRIVATE_KEY)
valid_signature = Base64.encode64(hash).chomp
unless params[:auth_signature] == valid_signature
api_not_authenticated
return
end
@current_user = user
end
end
def api_not_authenticated
render_api_message t("api.v1.unauthorized"), :unauthorized
end
end
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
@interface NSString (Extras)
+ (NSString *)authSignatureWithToken:(NSString *)token;
@end
@implementation NSString (Extras)
+ (NSString *)authSignatureWithToken:(NSString *)token
{
const char *cKey = [token cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [kApiSecretKey cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
length:sizeof(cHMAC)];
return [NSData base64WithData:HMAC];
}
@end
require 'securerandom'
class User < ActiveRecord::Base
before_create :generate_auth_token
def generate_auth_token
self.auth_token = SecureRandom.base64(30).tr('+/=lIO0', 'pqrsxyz')
end
end
- (void)fetchWidgets
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *authToken = [prefs objectForKey:kKeychainAuthToken];
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:authToken, @"auth_token", [NSString authSignatureWithToken:authToken], @"auth_signature", nil];
NSString *path = @"/api/v1/widgets.json";
NSString *resourcePath = [path stringByAppendingQueryParameters:params];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:resourcePath usingBlock:^(RKObjectLoader *loader) {
loader.delegate = self;
}];
}
@MSchmidt
Copy link

MSchmidt commented Jul 9, 2013

This is not secure at all. Your signature only contains the key and therefor this method doesn't provide any additional security over just using a plain auth token.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment