Quantcast
Channel: WCF, ASMX and other Web Services
Viewing all articles
Browse latest Browse all 555

How to call WCF service from Javascript using Basic Authentication?

$
0
0

Hello all,

I have a WCF service that is set to take Basic authentication. I have created a JS POC and trying to call WCF service thru it. I am passing credentials in javascript. Basically I wanted to implement Basic auth in JS.

My svc code: (Web.config)

<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<services>
<service name="BasicAuthenticationDemo.Service1">
<endpoint binding="webHttpBinding" contract="BasicAuthenticationDemo.IService1" bindingConfiguration="CustomBasicBinding" behaviorConfiguration="ServiceBehavior" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="CustomBasicBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="webBinding">
<security mode="Transport">
<transport clientCredentialType="Basic" proxyCredentialType="Basic"/>
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization serviceAuthorizationManagerType="BasicAuthenticationDemo.RestAuthorizationManager, BasicAuthenticationDemo"/>
<webHttp helpEnabled="True" />
<CorsSupport />
</behavior>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>

--------

[ServiceContract]
public interface IService1
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
string WelcomeUser(string userName);
}

---------

public class RestAuthorizationManager: ServiceAuthorizationManager
{
/// <summary>
/// Method source sample taken from here: http://bit.ly/1hUa1LR
/// </summary>
protected override bool CheckAccessCore(OperationContext operationContext)
{
WriteEventLog("CRM service authenticator: Step 1", EventLogEntryType.Error);
//Extract the Authorization header, and parse out the credentials converting the Base64 string:
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
WriteEventLog("CRM service authenticator:" + authHeader, EventLogEntryType.Error);
if ((authHeader != null) && (authHeader != string.Empty))
{
WriteEventLog("CRM service authenticator: authheader not null", EventLogEntryType.Error);
var svcCredentials = System.Text.ASCIIEncoding.ASCII
.GetString(Convert.FromBase64String(authHeader.Substring(6)))
.Split(':');
var user = new
{
Name = svcCredentials[0],
Password = svcCredentials[1]
};
WriteEventLog("CRM service authenticator: username=" + user.Name, EventLogEntryType.Error);
WriteEventLog("CRM service authenticator: password=" + user.Password, EventLogEntryType.Error);
if ((user.Name == "xxxtest\\xxx.crmdeploy" && user.Password == "xxx@"))
{
//User is authrized and originating call will proceed
return true;
}
else
{
//not authorized
return false;
}
}
else
{
//No authorization header was provided, so challenge the client to provide before proceeding:
WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"MyWCFService\"");
//Throw an exception with the associated HTTP status code equivalent to HTTP status 401
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}

private void WriteEventLog(string message, EventLogEntryType type)
{
const string sSource = "CRM service authenticator";
const string sLog = "Application";

if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);

EventLog.WriteEntry(sSource, message);
}
}

---------

My JS Code:

<!DOCTYPE html>
<html>
<head>
<title>Auth</title>
<meta charset="utf-8" />
<script type="text/javascript" src="jquery_2.0.3.min.js"></script>
<script type="text/javascript">
function CheckAuth() {
var crmProxy = "http://crm.com:555/dev_test/Service1.svc";
var name = "xxxtest\\xxx.crmdeploy";
var pwd = "xxx@";
var authorizationInfo = "Basic " + btoa(name + ':' + pwd);
var text = "Parshu";
var response = null;
$.support.cors = true;
$.ajax({
//async: true,
type: "POST",
url: crmProxy + "/WelcomeUser",
//xhrFields: {
// withCredentials: true
//},
//crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic " + authorizationInfo);
},
contentType: "application/json; charset=utf-8",
data: '{"userName": "' + text + '" }',
//headers: {
// "Authorization": "Basic " + authorizationInfo
//},
success: function (result) {
response = result.WelcomeUserResult;
alert(response);
},
error: function (xhr, ajaxOptions, throwError) {
//debugger;
alert("err");
}
});
}
</script>
</head>
<body>
<a>Auth example</a><br />
<input type="button" name="Submit" onclick="CheckAuth()" value="Submit" />
</body>
</html>

Request you to please guide me where I am going wrong. 

I am getting this error : XMLHttpRequest: Network Error 0x80070005, Access is denied.

-Prashant


Viewing all articles
Browse latest Browse all 555

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>