calling a wcf webapi service with basic authentication from an asp.net 2.0 project - asp.net-2.0

I'm working on a project that uses wcf webapi to expose all it's functionality as web services. I then consume these with various views (well two for now). One of these views is a legacy asp.net 2.0 project that will eventually be phased out once this new project has feature parity. I'm trying to consume these services by adding a service reference to the project but can't get it to work because the wcf api uses basic http auth and I can't configure that in the wizard. How do I manually add the service reference to my asp.net project?
Thanks!

When working with WCF Web API, you don't use service references but the new HttpClient instead e.g.:
var client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes(userName + ":" + password);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var task = client.GetAsync("http://webapi/contact/1");
var contact = task.ContinueWith(
t => {
return t.Result.Content.ReadAsAsync<Contact>();
}).Unwrap().Result;
If you need to use .NET 2.0, you can use the HttpWebRequest (the HttpClient sample relies on .NET 4.0 as it is part of WCF Web API):
Uri myUri = new Uri("http://webapi/contact/1");
WebRequest myWebRequest = HttpWebRequest.Create(myUri);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;
NetworkCredential myNetworkCredential =
new NetworkCredential(username, password);
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myNetworkCredential);
myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Credentials = myCredentialCache;
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream responseStream = myWebResponse.GetResponseStream();

Related

azure DevOps basic Auth using HttpClient (FAILED)

i am trying to Authenticate using HttpClient to my Azure Dev organization.
but its always failed.
the only way to achieve success with authentication was using Client Library like this:
VssConnection connection = new VssConnection(new Uri(azureDevOpsOrganizationUrl), new VssClientCredentials());
hope someone can tell me what is it the proper way to auth using username and password only.
UPDATE:
i also tried like this:
string SecurelyStoredUserName = "EmailAddressAsUserName";
SecureString SecurelyStoredPassword = new SecureString();
string PWD = "MyVerySecuredPassword";
PWD.ToList().ForEach(SecurelyStoredPassword.AppendChar);
NetworkCredential myCred = new NetworkCredential(
SecurelyStoredUserName, SecurelyStoredPassword, azureDevOpsOrganizationUrl);
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(SecurelyStoredUserName + ":" + SecurelyStoredPassword));
HttpClientHandler handler;
handler = new HttpClientHandler() { Credentials = myCred };
HttpClient client;
client = new HttpClient(handler);
client.BaseAddress = new Uri(azureDevOpsOrganizationUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + svcCredentials);
that what i did, but when i tried to do a get/post , i get Error 401 Unauthorized
You can't send a network credential to Azure Devops. It doesn't accept that kind of authentication. You could use a Personal Access token, or use the Active Directory API to get access.
All is explained on the very first "Getting started" pages on how to use the Azure DevOps APIs.
A complete sample for Interactive User+Pass auth is available here.
If you're trying to act as a user on-behalf-of, then you may need to rethink your approach.

A connection attempt failed because the connected party did not properly -- Using HttpClient

I am receiving connection attempt failed to my web api service when I called the service from asp.net mvc application. If I call the service from a browser or from MVC application hosted on another server, it works.
It also works if I host the application in test server or development server.
It doesn't work only when I host the application on that server and call the service from the mvc app.
Any suggestion. Is something on the hosted server is blocking the connection.
using (var client = new HttpClient())
{
string baseUrlFromConfig = ConfigurationManager.AppSettings["webServiceUrl"];
client.BaseAddress = new Uri(baseUrlFromConfig);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Uri myUri = new Uri(baseUrlFromConfig + "api/account/ConfirmEmail?e=" + e + "&code=" + code, UriKind.Absolute);
var response = client.GetAsync(myUri).Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
}
}

How to access a WCF REST Service inside .Net web application?

I have a WCF web service which returns a JSON string from a Silverlight appication. I want to parse this JSON string inside a controller method in another web application. I cant create a service reference to the WCF service I created in Silverlight in the web application since it is a REST service. How can I access this WCF REST service in the other application?
You should use something like the System.Net.WebRequest to call the WCF service in your controller.
There are a plethora of examples online on how to use it properly.
Personally, I use JSON.Net or AngularJS in all of my applications.
I was able to access the web service with the following code
using System.Net;
public string GetWebServiceData()
{
try
{
string requestUrl = "requesturl";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json";
request.ContentLength = 0;
request.Expect = "application/json";
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
return json;
}
catch (Exception)
{
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(string.Empty);
}
}
}

How to pass the credentials to consume an asmx service?

I am trying to consume a SAP web service in console application which requires authentication. I added the service reference to the console application.
ServiceReference1.SAPServiceSoapClient myService = new ServiceReference1.SAPServiceSoapClient();
System.Net.CredentialCache myCredentials = new System.Net.CredentialCache();
NetworkCredential netCred = new NetworkCredential("UserName", "Password");
Uri uriPrefix = new Uri("url");
myCredentials.Add(uriPrefix, "Basic", netCred);
//The following line is giving error that ClientCredentials cannot be assigned as it is read only.
myService.ClientCredentials = myCredentials;
We can use the following code:
AuthenticationToken token=new AuthenticationToken();
token.UserName="username";
token.Password="password";

Fail to connect an ASP.NET Web Client to a Web API 2.0 individual account authentication server

I am trying to connect an ASP.NET Single Page Application to a ASP.NET Web API 2.0 server with individual authentication. I am able to authenticate with the server using Fiddler and raw http requests as shown in the below tutorial:
Individual Accounts in Web API
My question is how do I point the separate single page client sample easily to the Web API service? Is it just a simple change in a configuration file or a connection string somewhere?
Surprisingly I cannot find that much info on how to do this on the web probably because it is deceptively simple and I am just missing something because I am new to ASP.NET
Update:
I basically want this to point to a different Web API 2.0 server:
static Startup()
{
PublicClientId = "self";
UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
....
}
That currently points to the root of the application but the Web API 2.0 server is actually on another ASP.NET Application running somewhere else.
This is all code you need to send request to Web Api 2.0:
//line below is for supporting self-generated ssl certificates, you can ommit if you're using http
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpClientHandler handler = new HttpClientHandler();
//this credentials will be in header
handler.Credentials = new NetworkCredential("someLogin", "somepassword");
client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:4567");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
mediaTypeFormatter = new JsonMediaTypeFormatter();
var content = new ObjectContent<T>(item, mediaTypeFormatter);
var response = await client.PostAsync("api/account/register", content);
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.BadRequest)
{
throw new ArgumentException("Internal server error");
}
//and here you have successfully sent request and received response from web api.
You can put it into some method then and use method parameters to pass for example host Uri. You can have that saved for example in Web.config as you mentioned.
So after working with the new ASP.NET MVC 5 and the Single Page Application templates in visual studio 2013 I found that the authentication and security is significantly different. This isn't so obvious from any of the documentation.
They both use the "new" ASP.NET Identity which replaces the older membership however when you use the ASP.NET MVC 5 template you get the same old SQL Server type of security setup through the controllers that used to be there, with the SPA (Single Page Application) Template you get API based token authentication.
The only way to wire up the SPA to another API 2.0 located somewhere else is on the client side of things on the JavaScript side, which is slightly confusing because that's not how the ASP.NET MVC 5 template works. The confusion comes from the fact that the SPA gives you both the server side and the client side setup.

Resources