We have a simple rest API exposed with Swagger UI. We usually copy-paste the raw definition to editor.swagger.io, and generate a C# client. The generated code works very well - but we work in a Windows AD environment, and we cannot find any way to tell the client to use the current user credentials during the communication. So the IIS hosted rest API throws Unauthorized exception - as it is set to Windows authentication mode.
Is it possible to use the generated client this way? Any option to add to the API definition to generate such a client?
Writing a client manually is easy:
var client = new WebClient();
client.UseDefaultCredentials = true;
...
but we would like to generate it ... but the Configuration contains nothing about credentials ... :(
public static IO.Swagger.Api.IBookingApi GetBookingApiWebApi()
{
var basePath = ConfigurationManager.AppSettings["web.api.url"];
var api = new BookingApi(basePath);
return api;
}
Thanks in advance...
Related
How to call Azure functions on azure from a Windows Application running on local machine, without embedding the keys in the Application?
Is there a Client Proxy Generator like the one for WCF Services but for Azure functions instead? or do you just use web client ?
You can use Restsharp to access an Azure Function.
You will need to get the full Url containg the host key from the portal.
Navigate to your function in the portal.
Use the </> Get function URL link for the function to get the full URL (next to the Run button at top of page). The key is after "code="
var fullUrl = "https://myfunciton1000.azurewebsites.net/api/ResourceGroupNameExists?code=ENp/dFAluLqHM8TDr...Sk5YJ7DSEbs0PHPzTVw==";
var url = "https://myfunciton1000.azurewebsites.net/api";
var securityCode = "ENp/dFAluLqHM8TDr...YJ7DSEbs0PHPzTVw==";
var client = new RestSharp.RestClient(url);
var request = new RestSharp.RestRequest("ResourceGroupNameExists", RestSharp.Method.POST);
request.AddHeader("x-functions-key", securityCode);
request.AddQueryParameter("ResourceGroupName", "ImageStormSource");
var response = client.Execute(request);
Calling an Azure function from a .NET application is simply a matter of issuing an HTTP request to the endpoint: https://social.msdn.microsoft.com/Forums/azure/en-US/2c676980-8dd3-4112-ae41-a2c4f4825fe3/how-to-call-a-azure-function-from-aspnet-webhook?forum=AzureFunctions
The communication between Azure and the client application is encrypted using SSL.
As far as the key is concerned, you could either hard-code it into your client code or configuration or retrieve it from some service of yours.
If your azure function app is using HttpTrigger it is no different than any non Azure WebAPI app. You call it via a rest client using either just basic a HttpClient or a wrapper library like RestSharp.
There is nothing special you have to deal with, go find any tutorial on how to call a WebAPI app for more information.
Your help is much appreciated.
I am trying to automate a web service call using C#. I managed to get it working from SoapUI. The service call requires authentication with valid username/pw as well as timestamp. But I don't know how to add this timestamp to C# service call.
Details of the web service.
URL: https://prod.decisionpoint3.com/fleet/bsm/api/JobExecutionService?WSDL
Authorization Basic
Credentials. Username:xxxx, Password:xxxx
In SoapUI, under Outgoing WS-Security Configurations, Add Username using the credential above and then add Timestamp, with Time to Live as 60
Details of request from SoapUI
request - getJobExecutions, raw XML as below
To Automate I created a C# Console application, added web reference as Veda. Code snippet as below
string username="xxxx";
string password="xxxx";
Veda.JobExecutionServiceImplService service = new Veda.JobExecutionServiceImplService();
System.Net.NetworkCredential credential=new NetworkCredential(username,password);
service.Credentials=credential;
service.Timeout = 1000;
Veda.JobDefinitionKey jobDefinitionKey=new Veda.JobDefinitionKey();
jobDefinitionKey.jobName="xxxx";
jobDefinitionKey.serviceFQN="Enterprise/Consumer/Term/ConsumerTermBusinessService";
jobDefinitionKey.templateName="ConsumerTermAUDataExtractCRM";
Veda.executionDateTimeRange executionDateTimeRange = new Veda.executionDateTimeRange();
executionDateTimeRange.startSpecified = false;
executionDateTimeRange.endSpecified = false;
Veda.JobExecution[] executions=service.getJobExecutions(jobDefinitionKey, executionDateTimeRange);
foreach(var exe in executions)
{
Console.WriteLine(exe.id);
}
My code threw an Service Access Violation exception because of this missing timestamp information.
your help in pointing the direction is much appreciated.
I know this is very common question. But I really do not know how to integrate it.
I want to add authentication to my web api services. Right now I have created one console application to call service's method.
I have gone through this blog. I just want to implement authentication filter as mentioned in this article.
I want to know how can I pass credentials along with HTTPClient from my console application, fetch those things to web API and authenticate them.
I have created authentication filter but it does not invoke AuthenticateAsync method of authentication filter.
To pass http client I have done this:
public void GetData()
{
HttpClient cons = new HttpClient();
cons.BaseAddress = new Uri("http://localhost:50524/");
cons.DefaultRequestHeaders.Accept.Clear();
cons.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = Encoding.ASCII.GetBytes("Ankita:ankita123");
var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(data));
cons.DefaultRequestHeaders.Authorization = header;
//MyAPIPost(cons).Wait();
MyAPIGet(cons).Wait();
}
Teaching you how to implement authentication in Web API will take a lot of time. You better stick to online tutorials.
The blog you've read tackles about different authentication for ASP.NET. Since you've tagged your question as ASP.NET Web API 2, I would suggest using a token-based authentication utilizing OWIN middleware. Check this out. The guide uses a console application for checking the requests to the web API.
The gist of it is...
Client > Token Provider (Generate token for valid user) > Web API > Check if Token is Valid (Existing and not expired) > Authenticate!
Considering you are trying to access the API with an HttpClient, you can pass it an instance of HttpClientHandler when creating it, which allows you to set the credentials that will be used when it performs requests:
new HttpClient(new HttpClientHandler { Credentials = new NetworkCredential(userName, password) })
Hope it helps!
I have successfully implemented authentication using this article. In that filter attribute is implemented.
I have a WCF service which is running fine.
It is used within an intranet network.
It is a self-hosted service
(no IIS) managed by a simple Windows Form program.
It is used by a
WCF client (WPF C#).
I now need to add security to it and after having read a lot of posts on the internet I'm getting confused as there are many ways of doing.
I need a custom username and password validator (I will have to call another web service to know if user is authorized or not).
I also need secure communication between client and server.
I am currently using basicHttpBinding.
MS recommends the use of NetTcpBinding in my case (https://msdn.microsoft.com/en-us/library/ff648863.aspx#TransportSecurityWCF), but I am not sure if this is or can be secured ?
I think I better use WsHttpBinding to have SSL: do you think that this link provides proper solution to my case ? https://msdn.microsoft.com/en-us/library/ms733775.aspx ?
Thanks for your advices
You can do SSL/Transport encryption with BasicHTTPBinding. That doesn't need to change; you just need to set up the host side with "Transport" security, add some code and a certificate, and you should be able to proceed without changing too much code. I can include a small code sample below, since I did the same thing you're trying to do via a self-hosted service.
BasicHttpBinding b = default(BasicHttpBinding);
if (bUseSSL) {
//check for ssl msg credential bypass
if (bSSLMsgCredentialBypass) {
b = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
} else {
b = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
}
b.TransferMode = TransferMode.Buffered;
b.MaxReceivedMessageSize = int.MaxValue;
b.MessageEncoding = WSMessageEncoding.Text;
b.TextEncoding = System.Text.Encoding.UTF8;
b.BypassProxyOnLocal = false;
//b.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
}
The authentication/authorization can be done, too, without changing what you currently have. You really have two choices:
One is that you create a Login function that get's called when the client first visits the host. You then send some token value back to the client for all subsequent communications.
The other way involves creating that custom authentication check, using the message inspector functionality found in Dispatcher.IDispatchMessageInspector and a public function called AfterReceiveRequest. Within that function, you can examine the UserID and Pwd (from within the HTTP header data) sent from the clients- but you need to implement this on both the client and host sides, otherwise it doesn't work.
I'm currently writing a C# metro app for the Windows 8 consumer preview which fetches some data from my REST-based web services. I want the app to authenticate against the services using the Windows Live account of the current user. Therefore, I added the Windows Live SDK to my solution and pasted the following snippet from the documentation into my login view:
LiveAuthClient liveClient = new LiveAuthClient();
LiveLoginResult loginResult = await liveClient.Login(new string[] { "wl.signin" });
After the login call has succeeded, I want to pass the encrypted AuthenticationToken of the LiveConnectSession via SSL to my webservice which should decrypt the token and read the information it is interested in (that's what the documentation suggests for such a SSO scenario). But sadly, the AuthenticationToken property of the session is always null. Am I missing something here?
I ran into the same problem and realised I had two issues with my configuration:
I didn't have a "Redirect domain" defined in the API settings of https://manage.dev.live.com
I wasn't using the overloaded LiveAuthClient constructor
For example in the API settings you specify:
Redirect domain: http://localhost/myapp
You then use the constructor overload of the LiveAuthClient:
var authClient = new LiveAuthClient("http://localhost/myapp");
var loginResult = await authClient.LoginAsync("wl-signin");
//this should no longer be null
var authToken = loginResult.Session.AuthenticationToken;
The redirect URI doesn't need to point to a working endpoint from what I can tell, as long as the two values match you should be in business.
Have you registered your app on the Live Connect app management site for Metro style apps? You need to register it here for it to work with Live Services. It will give you following instructions after you have given the app package a name and publisher.