How authenticate signed-in user via self-hosted WCF REST API - c#

I have a self-hosted WCF RESTful API that exposes some functionality that I don't want exposed to unauthorized users. All administrators must be signed in using a custom ASP.NET membership provider to call the REST API. Currently I just send a API key which is unsecure as it can be seen by all. All calls to the REST API is done via jQuery. I'm not using TLS/SSL or other transport security mechanisms. All REST API calls are done against the same server/domain, so there are no cross-domain calls or JSONP stuff going on.
My question is, what is the best practice in my case for securing my REST API? Perhaps I should use OAuth for this - the more I read about OAuth the more it seems it is not for my scenario with jQuery.
IVeraCMS.cs:
[ServiceContract]
public interface IVeraCMS {
[OperationContract]
[WebInvoke(Method = "GET",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string PerformanceCounter(string API_Key);
}
VeraCMS.cs:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall,
IncludeExceptionDetailInFaults = false, MaxItemsInObjectGraph = 1000)]
public class VeraCMS : IVeraCMS
{
public string PerformanceCounter(string API_Key)
{
if (ConfigurationManager.AppSettings["API_key"] != API_Key)
throw new SecurityException("Access denied");
var procPercentage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
procPercentage.NextValue();
var memPercentage = new PerformanceCounter("Memory", "Available MBytes");
memPercentage.NextValue();
const int samplingIntervalMs = 100;
Thread.Sleep(samplingIntervalMs);
var json = "{" + String.Format("\"ProcTime\":\"{0}%\",\"AvailMemory\":\"{1}MB\"" ,
procPercentage.NextValue().ToString(), memPercentage.NextValue().ToString()
) + "}";
return json;
}
}
}
Web.config:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="VeraWAF.WebPages.Interfaces.VeraCMS.Endpoint.Binding" maxReceivedMessageSize="4096" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="VeraWAF.WebPages.Interfaces.VeraCMS.Service.Behavior"
name="VeraWAF.WebPages.Interfaces.VeraCMS">
<endpoint address="" behaviorConfiguration="VeraWAF.WebPages.Interfaces.VeraCMS.Endpoint.Behavior"
binding="webHttpBinding" bindingConfiguration="VeraWAF.WebPages.Interfaces.VeraCMS.Endpoint.Binding"
contract="VeraWAF.WebPages.Interfaces.IVeraCMS" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="VeraWAF.WebPages.Interfaces.VeraCMS.Endpoint.Behavior">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="VeraWAF.WebPages.Interfaces.VeraCMS.Service.Behavior">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>

You can do basic HTTP authentication like this:
WebServiceHost secureHost
secureHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
secureHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new ClientValidator(username, password);
// Need to reference System.IdentityModel
public class ClientValidator : UserNamePasswordValidator
{
private readonly string _password;
private readonly string _username;
public ClientValidator(string username, string password)
{
_password = password;
_username = username;
}
public override void Validate(string userName, string password)
{
if (userName != _username || (password != _password))
{
WebFaultException rejectEx = new WebFaultException(HttpStatusCode.Unauthorized);
rejectEx.Data.Add("HttpStatusCode", rejectEx.StatusCode);
throw rejectEx;
}
}
}
Just keep in mind that your username and password can be easily sniffed if you are not using SSL. You can change the Validate method to fetch username and password from DB or some other service.

Related

How Create Get and Post Methods for the Login Page in wcf service in c#

I am creating a WCF service in ASP.NET and there i need to implement Get and Post Methods for simple Login page
This is for running the application on Local host.I have SQL server for the database.
C#:
This is the interface I have coded:
[ServiceContract]
public interface ILogin
{
[OperationContract(Name = "PostUserDetails")]
[WebInvoke(Method = "POST",UriTemplate = "")]
string UserName(Stream data);
string UserPassword(Stream data);
[OperationContract(Name = "GetUserDetails")]
[WebGet(UriTemplate = "GetUserDetails/inputStr/{name}")]
string UserName(string name);
string UserPassword(string name);
}
This is the class I have coded:
public class Login :ILogin
{
public string UserName(Stream data)
{
StreamReader streamReader = new StreamReader(data);
string xmlString = streamReader.ReadToEnd();
string returnValue = xmlString;
return returnValue;
}
public string UserPassword(Stream data)
{
StreamReader streamReader = new StreamReader(data);
string xmlString = streamReader.ReadToEnd();
string returnValue = xmlString;
return returnValue;
}
public string UserName(string strUserName)
{
StringBuilder strReturnValue = new StringBuilder();
// return username prefixed as shown below
strReturnValue.Append(string.Format("You have entered userName as {0}", strUserName));
return strReturnValue.ToString();
}
public string UserPassword(string strUserName)
{
StringBuilder strReturnValue = new StringBuilder();
// return username prefixed as shown below
strReturnValue.Append(string.Format("You have entered userName as {0}", strUserName));
return strReturnValue.ToString();
}
}
I have also configured the web.config as:
<system.serviceModel>
<services>
<service name="MyWCFService.Login" behaviourConfiguration ="loginbehaviour" >
<endpoint name="webHttpBinding" address="" binding="webHttpBinding" contract="MyWCFService.ILogin" behaviorConfiguration="webHttp">
</endpoint>
<endpoint name ="mexHttpBinding" address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyWCFServiceBehaviour">
<serviceMetadata httpGetEnabled="false"></serviceMetadata>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp"></behavior>
<webHttp/>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
I am getting HTTP Error 404.7 - Not Found Error
First of all you cant use Stream as your input. because stream con not serialized. then you don't need to create two separate methods. create login like this and use * as your Method. something like this:
[OperationContract(Name = "PostUserDetails")]
[WebInvoke(Method = "*",UriTemplate = "")]
string UserName(Data data);
string UserPassword(Data data);

Unable to define user/password for WCF service

I have a WCF web service working with basic authentification.
I want to define a user/password for this service. So I wrote my web.config to user basic authentification :
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="UsernameWithTransportCredentialOnly">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceWithMetaData">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization serviceAuthorizationManagerType="InterfaceWS.CredentialsChecker,App_Code.CredentialsChecker"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceWithMetaData" name="InterfaceWS.MyService" >
<endpoint
address="https://localhost:44336/MyService.svc"
binding="basicHttpBinding"
bindingConfiguration="UsernameWithTransportCredentialOnly"
name="BasicEndpoint"
contract="InterfaceWS.IErpService">
</endpoint>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="false" />
</system.serviceModel>
I created a class inherited from ServiceAuthorizationManager :
namespace InterfaceWS
{
public class CredentialsChecker : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
//Extract the Authorization header, and parse out the credentials converting the Base64 string:
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if ((authHeader != null) && (authHeader != string.Empty))
{
var svcCredentials = System.Text.ASCIIEncoding.ASCII
.GetString(Convert.FromBase64String(authHeader.Substring(6)))
.Split(':');
var user = new
{
Name = svcCredentials[0],
Password = svcCredentials[1]
};
if ((user.Name == "testuser" && user.Password == "testpassword"))
{
//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);
}
}
public override bool CheckAccess(OperationContext operationContext)
{
return false;
}
}
}
But the CheckAccessCore is never reached and i'm unable to connect to my Service. What did I do wrong ?
serviceAuthorization is about granting access to particular resources based on user credentials. You want authentication.
You can use serviceCredentials/userNameAuthentication tags in the configuration.
Example of configuration is given here: https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/membership-and-role-provider

WCF REST Service - HTTP 404 error while execution

I am using WCF REST service with basic authentication(UserName / Password) in IIS.
My interface - ICustomer.cs is as below:
namespace SampleService
{
[ServiceContract]
public interface ICustomer
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/Customer/{email}")]
string GetCustomerID(string email);
}
}
Customer.svc is as below:
<%# ServiceHost Language="C#" Debug="true" Service="SampleService.Customer" CodeBehind="Customer.svc.cs" %>
Customer.svc.cs:
namespace SampleService
{
public class Customer : ICustomer
{
public string GetCustomerID(string strEmail)
{
string returnJsonString = bllContactDetails.GetCustomerID(strEmail).ToString(Formatting.None);
WebOperationContext customContext;
customContext = Utility.General.SetCustomHttpStatusCode(returnJsonString);
return returnJsonString;
}
}
public class RestAuthorizationManager : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
//Extract the Authorization header, and parse out the credentials converting the Base64 string:
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if ((authHeader != null) && (authHeader != string.Empty))
{
var svcCredentials = System.Text.ASCIIEncoding.ASCII
.GetString(Convert.FromBase64String(authHeader.Substring(6)))
.Split(':');
var user = new { Name = svcCredentials[0], Password = svcCredentials[1] };
if ((user.Name == "testuser" && user.Password == "testpassword"))
{
//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);
}
}
}
}
I have added Web.Config as below:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"
httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization serviceAuthorizationManagerType=" SampleService.RestAuthorizationManager, SampleService"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpServiceBehavior">
<!-- Important this is the behavior that makes a normal WCF service to REST based service-->
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="SampleService.Customer" behaviorConfiguration="ServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="https://192.168.0.122:443/" />
</baseAddresses>
</host>
<endpoint binding="webHttpBinding" contract="SampleService.ICustomer" behaviorConfiguration="webHttpServiceBehavior" />
</service>
</services>
</system.serviceModel>
I have created Custom SSL and also enabled Basic Authentication in IIS.
When view my IIS hosted WCF service in browser it shows all the list of services.
But when I try to get data using Customer.svc method it is throwing error as below:
HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly.
Please find
Also, please let me know if it is the correct binding I'm using for obtaining Basic Authentication.

UNABLE to POST data to WCF from Android

I'm trying to send data to WCF service from an Android Application but somehow the service doesn't seems to be call through the android. I received a STATUSCODE value = 500 through adnroid in LOGCAT (which means the Internal Server Error) I go through the source code 100 times but didn't figure out the Bug. and almost checked all the posts related to my problem but still didn't get any solution.
HERE IS THS CODE
Android Code:
private class sendPostData extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpPost request = new HttpPost( LOGIN_SERVICE_URL + "/MyCar");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer getCarInfo;
try {
getCarInfo = new JSONStringer()
.object()
.key("myCar")
.object()
.key("Name").value(edt_carName.getText().toString())
.key("Make").value(edt_carMake.getText().toString())
.key("Model").value(edt_carModel.getText().toString())
.endObject()
.endObject();
StringEntity entity = new StringEntity(getCarInfo.toString());
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
txt_verif.setText("Success");
}
}
everything is working fine in android code except calling the WCF service. I Debug the code several times and received statuscode = 500
HERE is the WCF Service
Service.cs
public class Service1 : IService1
{
public void UpdateMyCar(myCar myCar) {
string strConnectionString = ConfigurationManager.ConnectionStrings["Database1"].ConnectionString;
SqlConnection conn = new SqlConnection(strConnectionString);
conn.Open();
using (SqlCommand cmd = new SqlCommand("Insert into TestingTable (Name,Make,Model) Values (#Name,#Make,#Model)", conn)) {
cmd.Parameters.AddWithValue("#Name", myCar.Name);
cmd.Parameters.AddWithValue("#Make", myCar.Make);
cmd.Parameters.AddWithValue("#Model", myCar.Model);
int queryResult = cmd.ExecuteNonQuery();
} conn.Close();
}
LogCat
WebInvoke Saving : 500
IService1.svc
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "MyCar",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
void UpdateMyCar(myCar myCar);
}
[DataContract]
public class myCar
{
[DataMember(Name="Name")]
public string Name
{
get;
set;
}
[DataMember(Name="Model")]
public string Model
{
get;
set;
}
[DataMember(Name="Make")]
public string Make
{
get;
set;
}
Web.Config
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0">
</compilation>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
<system.serviceModel>
<services>
<service name="CarSercive.Service1" behaviorConfiguration="CarSercive.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="webHttpBinding" contract="CarSercive.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CarSercive.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
this service is also publish on IIS. and I also checked that service with google chrome extension SIMPLE REST CLIENT and received an internal server error
The problem is your host name doesn't match what you are using from the phone.
You can turn off address filter to fix this temporarily:
[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]
public class Service1 : IService1
{
....
}
But you should fix the hostname when you release to production
Create a domain in your machine with proper port number and make sure you are able to call the service using the Google's Rest client.If it works,then you won't find any issue if you call the same using your android phone.
Following article will help to setup virtual directory with proper port number.[http://www.hosting.com/support/iis7/create-new-sites-in-iis-7/]
Note you can't call localhost directly from your mobile.atleast try to call the service with ipaddress.[http://localhost/service/mycar] =>[http://DemoService/service/mycar]
The following code will help you to debug your code a little bit deep.
catch (Exception ex)
{
WebException webexception = (WebException)ex;
var responseresult = webexception.Response as HttpWebResponse;
//Code to debug Http Response
var responseStream = webexception.Response.GetResponseStream();
string fault_message = string.Empty;
int lastNum = 0;
do
{
lastNum = responseStream.ReadByte();
fault_message += (char)lastNum;
} while (lastNum != -1);
responseStream.Close();
}
Never mind, I have made several changes in web.config file and got the solution. <endpointBehaviors> tag was missing in my case and several other things. here is the updated code of web.config file.
[UPDATED web.config file]
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings>
<add name="DB" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Munyb\Documents\Visual Studio 2010\Projects\CarSercive\CarSercive\App_Data\Database1.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
</compilation>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
<system.serviceModel>
<services>
<service name="CarSercive.Service1" behaviorConfiguration="RESTfulServ">
<!-- Service Endpoints -->
<endpoint address="" binding="webHttpBinding" contract="CarSercive.IService1" behaviorConfiguration="web"></endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="RESTfulServ">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
</modules>
</system.webServer>
</configuration>

WCF: Passing Username and password to another service (No Https)

I have to Create a WCF service (ServiceWrapper), which references another WCF Service(RealService).
I want Clients of ServiceWrapper to pass Username/password in authentication request.
The Operations of ServiceWrapper Call RealService. I need to pass the recieved Username/passowrd to Authenticate with RealSerivce and then call its Operations.
I need to host the service on Http and not Https(SSL/TLS).
Question: How to use the Client Credentails Recieved by a Service to authenticate with a Referenced Service without using Https(SSL/TLS)?
Your can use SOAP security. There are two SecurityModes for you - Message, TransportWithMessageCredential.
You should configure security mode (UserName) in <binding> section like this
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="" />
<message clientCredentialType="UserName" />
</security>
Next, you should specify custom validator in <behavior> section
<behavior name="CommonBehavior">
<serviceMetadata />
<serviceDebug includeExceptionDetailInFaults="True"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="Megatec.MasterTourService.CustomUserNameValidator, Megatec.MasterTourService"/>
<serviceCertificate findValue="WCFServer" storeLocation="LocalMachine"
storeName="My" x509FindType="FindBySubjectName"/>
<clientCertificate>
<authentication certificateValidationMode="PeerTrust" />
</clientCertificate>
</serviceCredentials>
</behavior>
In your custom validator you can access and store user name and password, which were given as creditionals for ServiceWrapper.
using System.ServiceModel;
using System.IdentityModel.Selectors;
namespace MyService
{
public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (!(userName == "testMan" && password == "pass"))
throw new FaultException("Incorrect login or password");
// save your Usermame and Password for future usage.
}
}
}
When you need to access RealService, you can use userName and password as credentials, like my example below:
private readonly Dictionary<Type, Object> channelFactoryDictionary = new Dictionary<Type, Object>();
private ChannelFactory<T> GetChannelFactory<T>() where T : class
{
if (channelFactoryDictionary.Keys.Contains(typeof(T)))
return channelFactoryDictionary[typeof(T)] as ChannelFactory<T>;
var channelFactory = new ChannelFactory<T>("*");
channelFactory.Credentials.UserName.UserName = userName;
channelFactory.Credentials.UserName.Password = password;
channelFactoryDictionary.Add(typeof(T), channelFactory);
return channelFactory;
}
If SSL is not an option, you will need to use SOAP message security (SecurityMode = Message).
http://msdn.microsoft.com/en-us/library/ms733137.aspx

Categories

Resources