Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
 have api_key, secret and I have to hash the signature to sha256. The signature = api_key+secret+utctimestamp. I am using Crypto.Js for hashing. I am getting following error

XMLHttpRequest cannot load "HOST LINK". No
'Access-Control-Allow-Origin' header is present on the requested resource. Origin localhost is therefore not allowed access

Following is my code

<script>
var app = (function($){

var baseURL = 'http://xyz.herokuapp.com/api/v1';
var apiSecretKey = 'ABC';
var apiKey = '123';
var init = function(){


$('#login').on('click', function(e){
    e.preventDefault();
    login();
});




};

var login = function() {

var u = encodeURIComponent($('#username').val());
var p = encodeURIComponent($('#password').val());

$.ajax({
    type: "POST",
    url: baseURL + "/login",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify({email: u, password: p}),      
    beforeSend: function (request) {
        request.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost');
        request.setRequestHeader('X-HASH', getHMAC(apiKey, timestamp));
    },
    success: function (data) {

    $('.loggedIn').show();
    console.log(data);
    $('.loggedIn .name').text("Hello ");
    },
    error: function (errorMessage) {
    alert('Error logging in');
    }
});
};


 timestamp = new Date().getTime() / 1000;;



var getHMAC = function(key, timestamp) {
    var hash = CryptoJS.SHA256(key+timestamp+apiSecretKey);
    return hash.toString();
};


return {
init:init
};
})(jQuery);

app.init();

Is the error due to wrong hashing or CORS problem. This is the first time I am using HMAC authentication, I don't know if I am doing it right or wrong.

Google developer tools give me this information![enter image description here][1]

REQUEST Method: OPTION Status Code: 200 Ok

Request Header Access-Control-Request-Headers:access-control-allow-origin, accept, content-type, x-hash Access-Control-Request-Method:POST

Response Header Allow:DELETE, POST, OPTIONS Connection:keep-alive Content-Length:0 Content-Type:text/html; charset=utf-8 Date:Mon, 04 Aug 2014 21:30:06 GMT Server:gunicorn/18.0 Via:1.1 vegur
Posted
Updated 28-Feb-18 5:08am

1 solution

Try converting the hash as base64 string like below-

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>

<script>
  var hash = CryptoJS.HmacSHA256("Message", "secret");
  var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
  document.write(hashInBase64);
</script>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900