Hello everyone, I am going to share the code sample how rest service authenticate using JSON Request.
Table of Contents
Need to add request headers to authenticate a wcf rest services using json request response. i.e.
beforeSend: function (xhr)
{
xhr.setRequestHeader("UserRoleId", "1");
xhr.setRequestHeader('Authorization Basic ', authenticatedByRequestHeader(username, pwd));
}
In the 2nd Step
Need to encrypt username and password and sent with heeder responses. i.e.
var username = "validate@gmail.com";
var pwd = "validate";
function authenticatedByRequestHeader(username, pwd)
{
var token = username + ':' + pwd;
var hashpwd = btoa(token);
return hashpwd;
}
Example for Authenticate REST WCF Services using JSON AJAX
var username = "authenticate@gmail.com";
var pwd = "authen@123# ";
function authenticatedByRequestHeader(username, pwd)
{
var token = username + ':' + pwd;
var hashpwd = btoa(token);
return hashpwd;
}
$(document).ready(function () {
$.ajax({
url: "https://192.168.1.11/UserService-20120830/GetUserService.svc/REST/",
type: "post",
dataType: "json",
data: {},
beforeSend: function (xhr) {
xhr.setRequestHeader("UserRoleId", "1");
xhr.setRequestHeader('Authorization Basic ', authenticatedByRequestHeader(username, pwd));
},contentType: 'application/json',
success: function (result) {
//Todo: if success, you implement your logic here..
},
error: function (jqXHR, txtStatus, errorsThrown) {
var errorMsg = '';
$('#msg').html(jqXHR.responseText);
}
});
});
Table of Contents
- First added to request headers for rest service authenticate.
- Encrypt the username and password and added in the heder.
Need to add request headers to authenticate a wcf rest services using json request response. i.e.
beforeSend: function (xhr)
{
xhr.setRequestHeader("UserRoleId", "1");
xhr.setRequestHeader('Authorization Basic ', authenticatedByRequestHeader(username, pwd));
}
In the 2nd Step
Need to encrypt username and password and sent with heeder responses. i.e.
var username = "validate@gmail.com";
var pwd = "validate";
function authenticatedByRequestHeader(username, pwd)
{
var token = username + ':' + pwd;
var hashpwd = btoa(token);
return hashpwd;
}
Example for Authenticate REST WCF Services using JSON AJAX
<script type="text/javascript">
var pwd = "authen
function authenticatedByRequestHeader(username, pwd)
{
var token = username + ':' + pwd;
var hashpwd = btoa(token);
return hashpwd;
}
$(document).ready(function () {
$.ajax({
url: "https://192.168.1.11/UserService-20120830/GetUserService.svc/REST/",
type: "post",
dataType: "json",
data: {},
beforeSend: function (xhr) {
xhr.setRequestHeader("UserRoleId", "1");
xhr.setRequestHeader('Authorization Basic ', authenticatedByRequestHeader(username, pwd));
},contentType: 'application/json',
success: function (result) {
//Todo: if success, you implement your logic here..
},
error: function (jqXHR, txtStatus, errorsThrown) {
var errorMsg = '';
$('#msg').html(jqXHR.responseText);
}
});
});
</script>