Firstly, I couldn't find an answer for my problem.
The problem is when I am making a call , I have to add the api key in the header. I am using Ajax but I dont want others seeing the api key from the devtool.
My code looks like this:
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:'/resource/auth/login',
data: {
username: username.value,
password:password.value
},
headers: { "ApiKey": "mykey" },
success: function(){
alert("Logged in");
Is there a way to hide the value of "mykey", the api call wont work if I dont provide the key in the header
Thanks in advance!
I hope I will work for you, this code for view:
#php
$secret_key = hash('sha256', 'some_secret_key');
$secret_iv = substr(hash('sha256', 'some_secret_iv'),0,16);
#endphp
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:'/resource/auth/login',
data: {
_token:{{csrf_token()}}
username: "{{openssl_encrypt('your_username','AES-256-CBC', $secret_key, 0, $secret_iv)}}",
password: "{{openssl_encrypt('your_password','AES-256-CBC', $secret_key, 0, $secret_iv)}}"
},
headers: { "ApiKey": "{{openssl_encrypt('your_apikey','AES-256-CBC', $secret_key, 0, $secret_iv)}}" },
success: function(resp){
console.log(resp);
},
error: function(err){
console.log(err);
}
}
);
in Controller's Function you can decrypt is to get username and password:
public function login(Request $request){
$secret_key = hash('sha256', 'some_secret_key');
$secret_iv = substr(hash('sha256', 'some_secret_iv'),0,16);
$username = openssl_decrypt($request->input('username'), 'AES-256-CBC', $secret_key, 0, $secret_iv);
$password = openssl_decrypt($request->input('password'), 'AES-256-CBC', $secret_key, 0, $secret_iv);
$apikey = openssl_decrypt($request->header('ApiKey'), 'AES-256-CBC', $secret_key, 0, $secret_iv)
echo 'Hye! your username is ' $username. ',your password is '. $password .'and your api key is '.$apikey;
}
here openssl_encrypt and openssl_decrypt are php functions, you can read about them in the documentation:
openssl_encrypt:
openssl_decrypt:
Make sure that your secret_key and secret_iv should be same on both sides.
Related
I'm trying to login in Joomla! by Ajax with default login module. But it always return success-
$('a.login_submit').click(function(e){
e.preventDefault();
$username = $('#username').val();
$password = $('#password').val();
$.ajax({
type: 'post',
url: 'index.php?option=com_ajax&module=login&method=user.login&format=json',
data: {username: $username, password: $password},
success: function(){
$('.error').hide();
$('.success').show();
},
error: function(){
$('.success').hide();
$('.error').show();
}
});
});
Why this always return true?
It'll be always a success (provided you have a connection with a server). You must analyse the response on success to validate the credentials.
success: function(data){
if ( data === "Correct" ) {
//handle login
}
else {
alert(data);
}
}
I have an MVC project secured with a asp.net identity:
This is my Login function:
self.login = function () {
event.preventDefault();
if (!$('#formLogin').valid()) {
return false;
}
var loginData = {
grant_type: 'password',
username: self.userName(),
password: self.password()
};
$.ajax({
type: 'POST',
url: '/API/Token',
data: loginData
}).done(function (data) {
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
self.authenticate();
//change status of Login button to Logout
self.redirect('Users');
}).fail(showError);
}
self.authenticate = function () {
self.token = sessionStorage.getItem(tokenKey);
var headers = {};
console.log(self.token);
if (self.token) {
headers.Authorization = 'Bearer ' + self.token;
}
$.ajaxSetup({
headers: headers
});
}
That works fine, I get the token successfully and the headers are set up correctly.
The problem is that when I try to send a request- for example:
self.getUsers = function () {
$.get("/API/Users/GetUsers/");
}
I get a 401 error from the server:
"message": "Authorization has been denied for this request."
What am I doing wrong?
According to the official documentation of the jQuery.ajax, use this to set custom headers of each request:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', '...');
}
});
I'm trying to use mcrypt and encrypt and decrypt json data crossing domain. Actually, this worked when I use the encryption in the same domain, but did not work in ajax.
Here is function all:
function all($contentType = 'page') {
$secret_key = "12345678911234567892123456789312";
$this->load->database();
$query = $this->db->query(
"SELECT * FROM category"
);
$buffer = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secret_key, json_encode($result), MCRYPT_MODE_ECB);
$this->output->set_output(base64_encode($buffer));
Here is file of view:
$(function(){
try {
$.ajax({
type: "GET",
url: "http://localhost:8888/DIY/index.php/user/all/json",
crossDomain: true,
contentType: "application/x-www-form-urlencoded",
async: false,
dataType: 'text',
processData: false,
cache: false,
success: function (response) {
var a = mcrypt.Decrypt($.base64('decode', response ));
console.log( JSON.parse(a) );
},
error: function (ErrorResponse) {
console.log('error');
}
});
}
catch (error) {
}
});
The output in Chrome is:
[{"id":"1","EMAIL":"sda#q.com","PHONE":"sdsng","USERNAME":"12das","FIRST_NAME":null,"LAST_NAME":null,"PASSWORD":"","TYPE":null},{"id":"2","EMAIL":"adas","PHONE":"dsada","USERNAME":"asdasd","FIRST_NAME":null,"LAST_NAME":null,"PASSWORD":"","TYPE":null}]
And if I add JSON.parse(a) in the view file, it will display nothing. However, after I get console.log(a) in Chrome, I directly copy the output data as the parameters, and use it in Chrome console
JSON.parse('[{"id":"1","EMAIL":"139520519#qq.com","PHONE":"yang_zhang","USERNAME":"122545929","FIRST_NAME":null,"LAST_NAME":null,"PASSWORD":"","TYPE":null},{"id":"2","EMAIL":"adas","PHONE":"dsada","USERNAME":"asdasd","FIRST_NAME":null,"LAST_NAME":null,"PASSWORD":"","TYPE":null}]')
[Object, Object]
The output is what I am looking for!!! Can anyone help me to solve this problem?
Now it is solved. I change the mode of mcrypt from ecb to cfb, and pass the IV to different domain. Then using passed IV to decrypt data will get the string which can use JSON.parse() to get expected json object
I'm making an ajax request to retrieve json data from webtrends - a service that requires a login. I'm passing the username and password in my ajax request, but still gives me a 401 unauthorized error. I've tried 3 different methods - but no luck. Can someone pls help me find a solution?
1. $.getJSON('https://ws.webtrends.com/..?jsoncallback=?', { format: 'jsonp', suppress_error_codes: 'true', username: 'xxx', password: 'xxx', cache: 'false' }, function(json) {
console.log(json);
alert(json);
});
2. $.ajax({
url: "https://ws.webtrends.com/../?callback=?",
type: 'GET',
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
username: "xxx",
password: "xxx",
beforeSend: function (req) {
req.setRequestHeader('Authorization', "xxx:xxx");
},
success: function (response) {
alert("success");
},
error: function(error) {
alert("error");
}
});
3. window.onload=function() {
var url = "https://ws.webtrends.com/...?username=xxx&password=xxx&callback=?";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
Method 3 might work when you use a named callback function and use basic authentication in the url. Mind though that a lot of browsers don't accept url-authentication (or whatever the name is). If you want to try it, you can rewrite it like this:
window.onload = function() {
var url = "https://xxx:xxx#ws.webtrends.com/...?callback=parseRequest";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
I have this simple Ajax code, my question is only, what does data.logged return, and what i need to have in the logged.php file...
I'm new to ajax, sorry for the dumb question...
$.ajax('logged.php', {
data: {
login: login,
pass: pass
},
success: function(data)
{
if (data.logged)
{
setTimeout(function() {
document.location.href = 'index.php'
}, 2000);
}
else
{
setTimeout(function() {
formLogin.clearMessages();
displayError('Utilizador ou password errados');
}, 2000);
}
},
error: function()
{
formLogin.clearMessages();
displayError('Error while contacting server, please try again');
}
});
On the client side, adding dataType : 'json' worked for me.
$.ajax('handler.php', {
data: {
login: login,
pass: pass
},
dataType : 'json',
success: function(data)
{
//code here
}
//more code here
}
And then on the server side:
$user = $_GET['login'];
$pass = $_GET['pass'];
$result = array();
if( /* login logic here */) {
$result['logged'] = 'true';
} else {
$result['logged'] = false;
}
header('Content-type: application/json');
echo json_encode($result);
That's a jQuery AJAX request which will be expecting responseText in JSON format. In this case, it seems like the JSON returned by your PHP file only needs to have a single property logged which will be either true or false depending on whether or not the login was successful.