How to pass the credentials to consume an asmx service? - asp.net

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";

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.

How can we send notifcation to authenticate user on Signalr which uses BackPlane?

We are using Azure Service Bus Topics as a backplane for signalR and we have at least 2 web instances.
We want to send a notification to a specific user with SignalR.
We are using "context.Clients.User" method on a web instance.
If the user is connected to this web instance and authenticated, he/she gets notification.
The problem is that: if the user is authenticated on other web instance, this does not work.
How can we send notification to user on another web instance ?
We are using Autofac.SignalR and SignalR.ServiceBus
IOC Configuration:
var builder = new ContainerBuilder();
.
.
.
.
.
Container = builder.Build();
RegisterGlobalCommonServiceLocator();
var resolver = new AutofacWebApiDependencyResolver(Container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
var connectionString = ConfigurationManager.AppSettings["SignalRBrokerServiceBus"];
var appName = ConfigurationManager.AppSettings["SignalRApplicationName"];
GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(Container);
var scaleOutConfig = new ServiceBusScaleoutConfiguration(connectionString, appName);
GlobalHost.DependencyResolver.UseServiceBus(scaleOutConfig);
Usage of contex ExchangeRate is derived class from Hub:
var user = _userService.FindById(orderBook.UserId);
var context =GlobalHost.ConnectionManager.GetHubContext<ExchangeRate>();
context.Clients.User(user.Email).deleteMyOrder(myOrder);
It's related with topic configuration on azure. We crated a topics with "enable partitioning". We were missing many messages.Now, Topics are created by IOC. It's work fine. I have tested on both instances. context.Clients.User works fine.

Testing a Web App Protected by Passive Federated Auth

My team has an ASP.NET MVC-based website and WebAPI that is protected by passive federated authentication. It all works properly. The problem we're having is that we need to test the website and the web API after an automated deployment. How can we authenticate and get the FEDAUTH cookie to the website from automated test code, assuming that the test code is run by a user authorized to access the website?
You can have your Web API support active authentication. It requires some work to change the configuration and authentication handler, but it will make your web API easily accessible from a program client as well. If you just want to get a FEDAUTH cookie in your automated test code, the following code sample can work. It mimics a browser to post the user token to the website and get a cookie back.
// The code needs the STS server and the website url
var stsUrl = "https://your_STS";
var serviceUrl = "https://your_Service";
// Use Windows Credential to get the token
var binding = new WSHttpBinding(SecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
var factory = new WSTrustChannelFactory(binding, stsUrl) { TrustVersion = TrustVersion.WSTrust13 };
// Override current login user credential if needed:
// factory.Credentials.Windows.ClientCredential = userCredential;
var rst = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
KeyType = KeyTypes.Bearer,
AppliesTo = new EndpointReference(serviceUrl)
};
RequestSecurityTokenResponse rstr;
var token = factory.CreateChannel().Issue(rst, out rstr);
var fedSerializer = new System.IdentityModel.Services.WSFederationSerializer();
var rstrContent = fedSerializer.GetResponseAsString(rstr, new WSTrustSerializationContext());
// After this the security token is acquired and saved in rstrContent
var client = new HttpClient();
// Initiate a request to the service, which will be redirected to STS. Read WS fed fields from redirected URL.
var response = client.GetAsync(serviceUrl).Result;
response.EnsureSuccessStatusCode();
var redirectQuery = response.RequestMessage.RequestUri.Query;
var queryParams = System.Web.HttpUtility.ParseQueryString(redirectQuery);
// construct a authentication form
var formData = new Dictionary<string, string>
{
{"wa", queryParams["wa"]},
{"wresult", rstrContent},
{"wctx", queryParams["wctx"] },
};
// post the authentication form to the website.
response = client.PostAsync(serviceUrl, new FormUrlEncodedContent(formData)).Result;
response.EnsureSuccessStatusCode();
// After this, the auth cookie is set in this HttpClient that you can use to access your service

Web request to 'https://accounts.google.com/o/oauth2/token' failed. No connection could be ...target machine actively refused it 173.194.70.84:443

I am building an application to fetch data via google analytics. For that purpose I have created a service account information from Google API console and in my .NET webform application successfully able to fetch data via following code:
string clientEmailId = ConfigurationManager.AppSettings.Get("clientEmailId");
string keyFile = AnalyticsKeyFileInitialPath + ConfigurationManager.AppSettings.Get("keyFile");
string keyPass = ConfigurationManager.AppSettings.Get("keyPass");
var desc = GoogleAuthenticationServer.Description;
var key = new X509Certificate2(keyFile, keyPass, X509KeyStorageFlags.Exportable);
var client = new AssertionFlowClient(desc, key) { ServiceAccountId = clientEmailId, Scope = scopeUrl };
var auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
var gas = new AnalyticsService(new BaseClientService.Initializer
{
Authenticator = auth
});
//auth.LoadAccessToken();
var accounts = gas.Management.Accounts.List().Fetch();
Now I am calling same code via WCF service but getting following error
Exception Message: Unable to connect to the remote server
Inner Exception: Web request to 'https://accounts.google.com/o/oauth2/token' failed.
Inner Exception: No connection could be made because the target machine actively refused it 173.194.70.84:443
Any idea what I could be doing wrong?

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

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();

Resources