Apex Web Service Authentication for .Net CF client - web-services

We are developing a barcode application to run on our mobile computers running Windows Mobile 5.0 Pocket PC and it needs to get it's data from our Oracle database.
Apex is already set up but how can I create a secure Web Service using Apex's native Authentication? How to set "HTTPS only"?
Update
I can call the ...?wsdl link in the browser now, looks fine. It's also registered in the project as a WebReferance.
But when I run the following code:
CONTAR_USUARIOSService service = new CONTAR_USUARIOSService();
System.Net.NetworkCredential pocket = new System.Net.NetworkCredential("pocket", "000");
service.Credentials = pocket;
double resultado = service.CONTAR_USUARIOS();
I get this error:
System.Net.WebException was unhandled
Message="WebException"
StackTrace:
at System.Web.Services.Protocols.SoapHttpClientProtocol.doInvoke(String methodName, Object[] parameters, WebClientAsyncResult asyncResult)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at Supernorte.Recebimento.ContarUsuariosWebReference.CONTAR_USUARIOSService.CONTAR_USUARIOS()
at Supernorte.Recebimento.Login..ctor()
at Supernorte.Recebimento.MainForm.mostrarLogin()
at Supernorte.Recebimento.MainForm..ctor()
at Supernorte.Recebimento.Program.Main()
I get an "Unauthorized" error.

If you get your Oracle inputs and outputs routed through your web service (which I am still personally struggling with), you might be able to access your information that way.
Add the web reference.
It will ask for the URL where your Web Service has been uploaded. I'm guessing this can be a website you own off site, but I use our internal server.
You can see I have a default web page where I load up the available services that I've stuck out there. 1Mainframe.svc` was going to be my "Big Service", but then I realized that I needed to do a lot more than make that once call, so I created the next one, "Erp Service".
Anyway, after I select the ErpService.svc, I'm given this, where I changed the default Web Reference Name to ErpService1. I've personally found that if I need to edit or modify the service, the XML config files get all messed up, so I just delete Service1 and add Service2.
I add a new class called ErpClass1.cs
Add a reference to my Web Service using the namespace for my project, and start coding!
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using AcpMobile5.ErpService1;
namespace AcpMobile5 {
class ErpClass1 {
private ErpService m_erpService;
public ErpClass1() {
m_erpService = new ErpService();
}
public void Query(string woNumber) {
m_erpService.Query(woNumber);
}
public string PartNumber() {
return m_erpService.CoilPartNo();
}
}
}
Obviously, this does not solve everything for you. The Web Service that you use to access your Oracle database still needs to be written, and that's no simple task.
However, I hope it helps point you along the right direction.
This is all done using Visual Studio 2008 for Mobile 5.0.

So, I didn't use Apex as I intended. Instead I enabled Oracle XML DB Native Web Services.
After some hard times with authentication [mostly caused by typing the wrong password ): ] I got this code working:
MyWebService service = new MyWebService();
service.Credentials = new MyWebService("MY_ORACLE_USER", "*******");
double result = service.MY_LOGIN_FUNCTION(this.userName);

Related

Host web UI with executable application?

This may be a very stupid question but I have spent nearly 5 hours doing research on the web and found nothing to fully clarify my doubts.
In few words I have been asked for a possible employer to develop certain executable application as part of a "Technical Test". Supposedly they're measuring my expertise working with WCF. I was given two days to develop such App and all the information about it is the following:
Deliverable:
                - An executable that
                                * When APP is ran, it should host a WCF service (SERVICE) as well as a
web UI (UI) accessible by web browsers.
                                * Through the UI, user should be able to add or delete messages stored in a
database (DB).
                                * The UI should also display the current list of messages stored in the DB.
                                * If changes are made to the DB, those changes should show up in the UI
without the need to reload the page.
                - All of the project source code.
               
Additional notes:
Use of existing libraries is allowed as long as they are clearly referenced
Now, I understand that you can host a WCF Web Service using a Console Application (among other options) and the Service will be alive as long as the application is running. I also know that any Web Application can access this service by just adding a Service Reference, creating a client of its type and calling its methods. My confusion begins when they ask me to put all together in one executable application:
When APP is ran, it should host a WCF service (SERVICE) as well as a web UI (UI) accessible by web browsers.
What is that supposed to mean?? How can I host a Web UI using an executable?? Am I supposed to develop something like IIS and at the same time somehow define the html and server side code on the APP?
I did some research and I found a class(HttpListener) that allows you to open an http port, listen and then send back some html thru it. A very simple class. If this is a solution I can't see how to implement it. Other than that I couldn't find anything else on the web.
I would appreciate any opinion on the matter, even if I'm not able to develop the solution in time I would like to know how to do it. And if I'm missing some important basic concept regarding WCF or Web Hosting please I would greatly appreciate some clarification. Thanks in advance.
You can use OWIN to "self host" web apps.
An overview and further information can be found here - http://codeopinion.com/self-host-asp-net-web-api/
I solved the problem by hosting the web UI in the service itself. A service operation can return anything, even a Stream of bytes with the html for the browser to render. Here's the code.
[WebGet(BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public Stream GetUserInterface()
{
var appDirectoryName = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var htmlFilePath = appDirectoryName + "\\UI.html";
var buffer = File.ReadAllBytes(htmlFilePath);
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return new MemoryStream(buffer);
}
As you can see on the same directory than the executable I placed a UI.html file, this file contains all my UI html, javascript and css. Then I convert it to an array of bytes and return that to the browser.
So the only thing I have to do to access the UI is run the application and then browse to this operation. Eg: http://localhost:8080/MyService/GetUserInterface.
For the database part I used SQlite, in this way the application became a standalone that can be installed in a PC and run immediately without the need of Database or Web hosting. Exactly what the test requested.
Alternatively the class that I mentioned in my question (HttpListener) can also be used to host the Web UI instead of the service. This is another solution.
private static void HostUI()
{
while (true)
{
using (var listener = new HttpListener())
{
listener.Prefixes.Add("http://localhost:7070/");
listener.Start();
var context = listener.GetContext();
var response = context.Response;
//The .html file will be in the same folder where the .exe is
var appDirectoryName = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var htmlFilePath = appDirectoryName + "\\UI.html";
var buffer = File.ReadAllBytes(htmlFilePath);
response.ContentType = "text/html";
response.ContentLength64 = buffer.Length;
Console.WriteLine(buffer.Length);
var output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
listener.Close();
}
}
}
The reason why I used an infinite loop is because the HttpListener class implementation processes only one order by loop, so in order to able to request the UI multiple times you need to do this.
Then you can browse to http://localhost:7070/ and you'll see the UI too.
You can put this code in an independent thread to host the Web UI without affecting the main thread.

How to attach X509Certificate2 to webservice (Apple GSX / C# specific)

Apple released their New Generation WSDL on the 15 of August this year (2015) and the big change was that every call to the WSDL had to be validated with a certificate file.
I've done the process to get the certificate from Apple, and I've whitelisted our server IP, and I've even verified that I can get access to the service endpoint from our server by coding a simple interface using HttpWebRequest where I easily can attach the certificate using webRequest.ClientCertificates.Add(), so I know everything is ready for it to work.
But, my problem arises when I download the WSDL from https://gsxwsut.apple.com/apidocs/prod/html/WSArtifacts.html?user=asp
I import the WSDL into Visual Studio and when I try to make an instance of the client class, the only one I find is GsxWSEmeaAspPortClient, which seems to be correct as it has all the functions for authenticate and various tools, but it does not have ClientCertificates. It does have ClientCredentials which have ClientCertificate, but when I try to set the cert there, it's as tho it's never set.
I'm guessing the service code transmits the data via either HttpWebRequest or WebRequest, so if I just can get to the request code from my instance of the class (GsxWSEmeaAspPortClient) I can probably fix it, but I can't seem to get there.
I've looked at this question: How can I connect with Apple's GSX NewGeneration webservices with WCF? which suggests it really should be that easy, but I don't have the GsxWSEmeaAspService, only the GsxWSEmeaAspPortClient from my Visual Studio's generation of the WSDL.
If anyone has any ideas which can point me in any direction towards victory I'd be eternally grateful.
I'm using Visual Studio 2013 and the solution is .Net v4.5.1 if that makes any difference.
I've pasted new code here:
public void Authenticate() {
// Use custom binding with certificate authentication
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
// Create service endpoint
// Use proper endpoint address - eg. gsxapi.apple.com for production
EndpointAddress endpoint = new EndpointAddress("https://gsxapiit.apple.com/gsx-ws/services/emea/asp");
// Create new service
Apple.GsxWSEmeaAspPortClient service = new Apple.GsxWSEmeaAspPortClient(binding, endpoint);
// Set loaded certificate
service.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(
"[PathToContainerFromStep7].p12",
"[YourPasswordFromStep8]");
// Create authenticate request object
Apple.authenticateRequestType auth = new Apple.authenticateRequestType()
{
languageCode = "en",
userId = "[YourAppleServiceAccountNumber]",
userTimeZone = "[YourTimeZone]",
serviceAccountNo = "[YourSoldToNumber]"
};
// Authenticate to Apple GSX
Apple.authenticateResponseType session = service.Authenticate(auth);
// Assign your new session id object
userSessionId = new Apple.gsxUserSessionType() { userSessionId = session.userSessionId };
}

How to have a webmethod POST to an HTTPHandler.ashx file

Summary
How to create an HTTPContext within a webservice? or POST to a Handler.ashx from a webservice?
Background
I have a Cold Fusion web application that uses Forms authentication but somehow achieves Windows authentication with this script:
<cfscript>
ws = CreateObject("webservice", "#qTrim.webServiceName#");
ws.setUsername("#qTrim.trimAcct#");
ws.setPassword("#qTrim.trimpwd#");
wsString=ws.UploadFileCF("#qTrim.webserviceurl#","#objBinaryData#", "#qFiles.Filename#", "Document", "#MetaData#");
</cfscript>
Apparently, the setUsername/setPassword values map to a single Windows domain account and this works in production. (The webservice is written in C# and built with .Net 4.0. and it must be used by this domain account)
I developed a DownloadHandler.ashx which works when POSTed to by a process which is running under this domain account (I have a .Net web client with a button that defines PostBackUrl="~/DownloadHandler.ashx"). This HTTPHandler grabs a few items from the HTTPContext and then calls the above webservice method DownloadFile without problems.
My Problem
Now this ColdFusion app needs to download a file using this webservice. When the CF code POSTs an HTML form to the DownloadHandler.ashx it works - BUT ONLY IF the CF tester is using this Windows domain account. This won't work in production because the CF app supports remote anonymous users through forms authentication.
Question
Not knowing ColdFusion myself, I was thinking of the following changes:
Replicate the above CF technique such that user/pswd can be set the same and have CF invoke the ws.DownloadFile method directly
I think this would require using most of my current HTTPHandler code in my webservice but I cannot think of how to handle the output. When this handler is POSTed to, it prompts for OPEN or Save and works nicely but I'm confused on how I would stream this back from the webservice itself.
The current DownloadFile webmethod communicates with a database product and returns output to this (the current) handler:
Code
namespace WebClient
{
public class DownloadHandler : IHttpHandler
{
ASMXproxy.FileService brokerService;
public void ProcessRequest(HttpContext context)
{
brokerService = new ASMXproxy.FileService();
string recNumber = context.Request.Form["txtRecordNumber"];
brokerService.Url = context.Request.Form["txtURL"];
string trimURL = context.Request.Form["txtFakeURLParm"]; // not a real URL but parms to connect to TRIM
brokerService.Timeout = 9999999;
brokerService.Credentials = System.Net.CredentialCache.DefaultCredentials;
byte[] docContent;
string fileType;
string fileName;
string msgInfo = brokerService.DownloadFile(trimURL, recNumber, out docContent, out fileType, out fileName);
string ContentType = MIMEType.MimeType(fileType);
context.Response.AppendHeader("Content-Length", docContent.Length.ToString());
context.Response.AppendHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
context.Response.ContentType = ContentType;
context.Response.OutputStream.Write(docContent, 0, docContent.Length);
context.Response.OutputStream.Flush();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Assuming your CF site is running on IIS and not Apache or some other web server, this might work:
Put your .cfm file that calls the webservice into its own subfolder on your site. Set the Authentication properties of that folder to use Anonymous Authentication, but set the user identity to the Windows Domain account that successfully calls the webservice (click the Set... button on the dialog shown below and enter the appropriate credentials).

Calling a custom SharePoint web service from ASP.Net AJAX gives a 403 error?

I have developed a custom SharePoint web service, and deployed it to /_vti_bin/myservice.asmx. As a "regular" user, browsing to that ASMX URL works fine. When I try to browse to "/_vti_bin/myservice.asmx/js" as required to call this service from ASP.Net AJAX, I get a 403. If I browse to it as no less than a farm admin (site collection admin doesn't work), I get a 403. It is entirely possible that the farm admin's role as a local server admin is also allowing it to work.
This is my web service class:
[WebService(Namespace = "http://sharepointservices.genericnamespace.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class ApprovalSvc : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDocument GetInboxItems(string inboxName, string s_Id)
{
// code removed
}
}
This is the art of my web part code where I am hooking up the ASP.Net AJAX stuff:
ScriptManager scriptMgr = new ScriptManager();
string webUrl = SPContext.Current.Web.Url;
ServiceReference srvRef = new ServiceReference(webUrl + "/_vti_bin/ApprovalSvc.asmx");
scriptMgr.Services.Add(srvRef);
this.Controls.Add(scriptMgr);
If I'm logged in as a farm/server admin, it works. Otherwise, no. The web service assembly is in the GAC & listed in SafeControls. Any ideas?
Good old Process Monitor to the rescue.
The facts:
The service code DLL is in the web application's bin directory, as it cannot be signed b/c it references unsigned DLLs.
The request for the service DLL is coming from ASP.Net & not SharePoint, specifically an HttpModule in the System.Web.Extensions assembly.
The solution:
Because the request didn't come through SharePoint, and identity impersonation is also turned on by default, the default NTLM permissions on the web app's BIN directory were not good enough - the user's account had no access to the BIN directory or the DLLs within it.
We gave the NT AUTHORITY\Authenticated Users Read access (not Read & Execute, not List Folder Contents, just Read) to the folder, and all is well.

Login failed when a web service tries to communicate with SharePoint 2007

I created a very simple webservice in ASP.NET 2.0 to query a list in SharePoint 2007 like this:
namespace WebService1
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string ShowSPMyList()
{
string username = this.User.Identity.Name;
return GetList();
}
private string GetList()
{
string resutl = "";
SPSite siteCollection = new SPSite("http://localhost:89");
using (SPWeb web = siteCollection.OpenWeb())
{
SPList mylist = web.Lists["MySPList"];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name=\"AssignedTo\"/><Value Type=\"Text\">Ramprasad</Value></Eq></Where>";
SPListItemCollection items = mylist.GetItems(query);
foreach (SPListItem item in items)
{
resutl = resutl + SPEncode.HtmlEncode(item["Title"].ToString());
}
}
return resutl;
}
}
}
This web service runs well when tested using the built-in server of Visual Studio 2008. The username indicates exactly my domain account (domain\myusername).
However when I create a virtual folder to host and launch this web service (still located in the same machine with SP2007), I got the following error when invoking ShowSPMyList() method, at the line to execute OpenWeb(). These are the details of the error:
System.Data.SqlClient.SqlException: Cannot open database "WSS_Content_8887ac57951146a290ca134778ddc3f8" requested by the login. The login failed.
Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.
Does anyone have any idea why this error happens? Why does the web service run fine inside Visual Studio 2008, but not when running stand-alone? I checked and in both cases, the username variable has the same value (domain\myusername).
Thank you very much.
Thank you very much for the replies. I'll look into the documents to see how i can change the settings related to the application pool as suggested.
I want to make clear that i wanted to build a webservice to run outside of sharepoint (but can be deployed on the same server with sharepoint).
Is there any way i can programmatically pass the credentials (another domain account instead of 'NT AUTHORITY\NETWORK SERVICE' by default) to sharepoint when invoking OpenWeb method? I believe if i'm able to do that then i can walkaround the security issue above.
When you create your own custom virtual folder and set it inside the IIS, it's highly possible that the user account who run the application pool of that particular IIS virtual directory is currently set to NT authority\Network Service.
You can check carefully, by looking closely of what is the actual application pool that run that particular IIS virtual directory.
From there, you can go to the "Application Pool" folder and right click, choose Properties. Select the "Identity" tab, and it will show you who is the user account that currently running the application pool.
Alternatively, you can refer to the SharePoint SDK, something similar to ExtractCrmAuthenticationToken in dynamics CRM to extract the Authentication Token ticket.
Or alternatively you can use Network Credential to embed your own custom user id and password.
Hope this helps,
hadi teo
I fully agree with Hadi, if this is something you want to just quickly test, for a proof of concept, you can change the credentials under what the Application pool runs, to a user that has permissions. Or you could use Identity Impersonate setting in your config file.
However resist the temptiation to do this in a production enviroment, use the proper authentication. It will come back, to bite you.
If you need to set this up for production, there is a couple of areas that you want to look at, duplicate SPN's, and deligation probably the most common areas that is not configured correctly. Your error however points to impersanation not happening.
Also make sure you are deploying the web service to its own web site that does not already run SharePoint. If you want the web service to run on the same web site as SharePoint read Creating a Custom Web Service.
You can check what application pool identity SharePoint is using by following the same instructions that Hadi writes, but for an app pool running SharePoint. Make sure to only change the application pool used by your web service and not SharePoint or else other permission errors could occur within SP. (There should be no reason but if you are interested in changing the app pool identity used by SharePoint follow these instructions.)
On solution would be to "impersonate" as the SharePoint System account using the following code:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// also dispose SPSite
using (SPSite siteCollection = new SPSite("http://localhost:89"))
{
using (SPWeb web = siteCollection.OpenWeb())
{
// ...
}
}
});