the following VB.net code is working to authenticate to a web service - and it works great however i am having to use default network Credentials ( the logged in user the code runs under )
I would like to pass network Creds to the web service and the following should work but does not. This is the working code using default credentials.
Dim URL As String = "http://server/MBSDKService/MsgSDK.asmx?WSDL"
Dim myService As New LANDeskMBDSK.MBSDK
myService.Url = URL
Dim CredCache As New System.Net.CredentialCache
myService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
This is what i want to work but does not...
Dim URL As String = "http://server/MBSDKService/MsgSDK.asmx?WSDL"
Dim myService As New LANDeskMBDSK.MBSDK
myService.Url = URL
Dim Cred As New System.Net.NetworkCredential("domain\user", "password")
Dim CredCache As New System.Net.CredentialCache
CredCache.Add(New Uri(myService.Url), "Basic", Cred)
myService.Credentials = CredCache
Does anyone know what I am doing wrong?
The rest of the code works perfectly so it is a case of what i have to add to the above to get it to work like the default credentials do.
Thanks!
Thanks to George this is the solution...
Dim URL As String = "http://server/MBSDKService/MsgSDK.asmx?WSDL"
Dim myService As New LANDeskMBDSK.MBSDK
myService.Url = URL
Dim Cred As New System.Net.NetworkCredential("user", "password")
Dim CredCache As New System.Net.CredentialCache
CredCache.Add(New Uri(myService.Url), "Basic", Cred)
myService.Credentials = Cred
Try any of these:
Dim Cred As New System.Net.NetworkCredential("user", "password", "domain")
Dim Cred As New System.Net.NetworkCredential("user", "password")
Whats the actual error message?
EDIT:
This seems to be working:
myService.Credentials = Cred
Related
When i make third party request to some URL then IIS gives me error:
The request was aborted: Could not create SSL/TLS secure channel.
however i am able to make request to same URL from console application and Postman.
Dim certificates As X509Certificate2 = New X509Certificate2()
Dim uriPath As String = "D:\CertificateFolder\MyCert.cer"
Dim localPath As String = New Uri(uriPath).LocalPath
certificates.Import(localPath)
Dim sResult As String = ""
Dim activeProtocol As SecurityProtocolType =
ServicePointManager.SecurityProtocol
Try
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or
SecurityProtocolType.Tls11
Dim oRequest As HttpWebRequest =
WebRequest.Create("https://test.com/router.dll")
oRequest.KeepAlive = False
oRequest.Method = "POST"
oRequest.ContentType = "text/xml"
Dim Test As String = "some xml"
Dim bytes As Byte() = Text.Encoding.UTF8.GetBytes(Test)
oRequest.ContentLength = bytes.Length
oRequest.ClientCertificates = New X509CertificateCollection({certificates})
Dim oWriter As StreamWriter
Try
Dim streamToSend As Stream = oRequest.GetRequestStream()
oWriter = New StreamWriter(oRequest.GetRequestStream())
streamToSend.Write(bytes, 0, bytes.Length)
streamToSend.Close()
Catch up As Exception
Return
Finally
End Try
Dim oResponse As HttpWebResponse = oRequest.GetResponse()
Dim oReader As New StreamReader(oResponse.GetResponseStream())
sResult = oReader.ReadToEnd
oReader.Close()
Catch
' do nothing for now
Finally
ServicePointManager.SecurityProtocol = activeProtocol
End Try
Note* Method in URL is not file. Method name has .dll just as name of method.
I am using .net framework 4.5
Do you have access to the server management?
Could you first try to connect without providing the client certificate?
Remove the corresponding part from your code and turn off the client certificate requirement in the IIS management console.
If the error still persist, find out which cipher suits the client supports and which the server. If they don't much an error similar to yours would occur.
To check the client, rewrite your code to connect to the following site:
"https://howsmyssl.com/a/check"
If your server you are connection to is public (internet visible), you can use the following site to check its supported cipher suits:
https://www.ssllabs.com/ssltest/
I trying get a simple request to https://c-cex.com/t/prices.json
If i use this url in browser the correct response is showed , but if i make the same request using RestRequest i receive the 403 error Forbidden in all times. i trying HttpClient,WebRequest i get the same error
I put the header with user-agent, no cache and a lot of another values but did not work
Any ideas about this problem?
Dim url As String = "https://c-cex.com/t/prices.json"
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
Dim response = client.Execute(request)
Updated code with apisign request
Dim nonce As String = CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString
Dim url As String = "https://c-cex.com/t/api.html?a=getbalance¤cy=BTC&apikey=" & API_KEY & "&nonce=" & nonce
Dim keybytes() = UnicodeEncoding.ASCII.GetBytes(API_SECRET)
Dim hs As System.Security.Cryptography.HMACSHA512 = New System.Security.Cryptography.HMACSHA512(keybytes)
Dim urlbytes() = UnicodeEncoding.ASCII.GetBytes(url)
Dim sh() = hs.ComputeHash(urlbytes)
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
request.AddHeader("Cache-Control", "no-cache")
request.AddHeader("apisign", HttpUtility.UrlEncode(ToHexString(sh)))
Dim response = client.Execute(request)
I am getting the response without providing the header information and It looks given piece of code is working correctly for me in VB and C#.As a best practice, base URL needs to be specified in RestClient and relative URL in RestRequest.
Please recheck without adding the request header information
VB:
Imports RestSharp
Module Module1
Sub Main()
Dim host As String = "https://c-cex.com"
Dim endpoit As String = "t/prices.json"
Dim client As New RestSharp.RestClient(host)
Dim request = New RestRequest(endpoit, Method.GET)
Dim response = client.Execute(request)
Console.WriteLine("Response Body " + response.Content)
Console.WriteLine("Response Code " + response.StatusDescription)
End Sub
End Module
C#:
String host = "https://c-cex.com";
String endpoint = "t/prices.json";
RestClient _restClient = new RestClient(host);
var request = new RestRequest(endpoint, Method.GET);
var response = _restClient.Execute(request);
Console.WriteLine("Response Body :"+response.Content);
Console.WriteLine("Response Status Code :" + response.StatusDescription);
I am writing a windows service application in Visual Studio (VB) that polls a users google calendar for any events that are happening within the next 5 minutes.
Ideally, I'd like my service to generate the credentials, but I don't think a windows service can pop up a browser page to authenticate someone. Currently I am generating the credentials in a specific location from a console app that can pop up a browser, and having the service look for credentials in that location. I'd like to get rid of the console app altogether, but if it's necessary I'll just run it in the batch file that installs the service.
The big issue I'm having is generating the credentials file (secondary concern), and more importantly refreshing it so it doesn't expire after an hour (primary concern).
Here is my windows service code (this works perfectly fine for the hour after I run my console app and allow access to my calendar):
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Private Sub writeUpdateTimerEvent(source As Object, e As ElapsedEventArgs)
Dim credential As UserCredential
Try
Using stream = New FileStream("FILE PATH TO client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "FILE PATH TO WHERE MY CONSOLE APP IS STORING THE CREDENTIALS FILE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
If credential Is Nothing Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.TimeMax = DateTime.Now.AddMinutes(5)
request.ShowDeleted = False
request.SingleEvents = True
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim eventsString As String = ""
Dim events As Events = request.Execute()
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
'This is where I do my operations on events occuring in the next 5 minutes
EventLog1.WriteEntry("Event occuring within 5 minutes")
Else
EventLog1.WriteEntry("No event occuring within 5 minutes")
End If
Catch ex As Exception
EventLog1.WriteEntry("error grabbing events." & Environment.NewLine & ex.message)
End Try
End Sub
Here is my console app code (pretty much the same as above):
Module Module1
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Sub Main()
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "SAME FILE PATH AS IN MY SERVICE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.ShowDeleted = False
request.SingleEvents = True
request.MaxResults = 10
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim events As Events = request.Execute()
Console.WriteLine("Upcoming events:")
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
For Each eventItem As Object In events.Items
Dim [when] As String = eventItem.Start.DateTime.ToString()
If [String].IsNullOrEmpty([when]) Then
[when] = eventItem.Start.[Date]
End If
Console.WriteLine("{0} ({1})", eventItem.Summary, [when])
Next
Console.WriteLine("You may now close this window.")
System.Environment.Exit(0)
Else
Console.WriteLine("No upcoming events found.")
End If
Console.Read()
End Sub
End Module
Got it working now, using a service account instead of a user account. No need for dealing with generating credentials or refreshing the token.
Dim serviceAccountEmail As [String] = ConfigurationManager.AppSettings("ServiceAcct")
Dim certificate = New X509Certificate2("key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim credential1 As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = Scopes
}.FromCertificate(certificate))
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential1,
.ApplicationName = ApplicationName
})
My code is below. credential contains a token.
Settings contains a subtoken and the application name, but nothing else.
I am not sure if it is authenticating. Token, token secret, privatekey are all nothing.
Dim _Scopes As New List(Of String)
_Scopes.Add("https://www.google.com/m8/feeds")
_Scopes.Add("http://www.google.com/m8/feeds/contacts/")
_Scopes.Add("https://www.googleapis.com/auth/contacts.readonly")
Dim certificate As X509Certificate = New X509Certificate2("c:\sites\key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim serviceAccountEmail As String = "serviceaccountemailhere"
Dim credential As ServiceAccountCredential = New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {.User = serviceAccountEmail, .Scopes = _Scopes}.FromCertificate(certificate))
Dim settings As RequestSettings = New RequestSettings("Gmail Contact APP", Await credential.GetAccessTokenForRequestAsync())
Dim cr As New ContactsRequest(settings)
For Each ct In cr.GetContacts.Entries
Console.Write(ct.ContactEntry.Name)
Next
NOTE: I've never written vb.net code before this. I've googled for a solution but did not find anything that worked.
I'm trying to get access token from Salesforce. Below code worked just yesterday. And I have no idea why it is not working today. I've tried adding content-type as application/x-www-form-urlencoded but it did not work either. When I use curl I'm able to get access token. Also I'm able to get access token using advanced rest client in google chrome. Any ideas why it is returning 400 Bad Request unknown error retry your request?
Imports System.Collections.Specialized
Imports System.Net
Imports System.Text
Module Module1
Sub Main()
Dim clientId As String = "clientId"
Dim clientSecret As String = "clientSecret"
Dim redirectUri As String = "https://test.salesforce.com"
Dim environment As String = "https://test.salesforce.com"
Dim tokenUrl As String = ""
Dim username As String = "username#salesforce.com"
Dim password As String = "passwordtoken"
Dim accessToken As String = ""
Dim instanceUrl As String = ""
Console.WriteLine("Getting a token")
tokenUrl = environment + "/services/oauth2/token"
Dim request As WebRequest = WebRequest.Create(tokenUrl)
Dim values As NameValueCollection = New NameValueCollection()
values.Add("grant_type", "password")
values.Add("client_id", clientId)
values.Add("client_secret", clientSecret)
values.Add("redirect_uri", redirectUri)
values.Add("username", username)
values.Add("password", password)
request.Method = "POST"
Try
Dim client = New WebClient()
Dim responseBytes As Byte() = client.UploadValues(tokenUrl, "POST", values)
Dim response As String = Encoding.UTF8.GetString(responseBytes)
Console.WriteLine(response)
Console.ReadKey()
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.WriteLine("Press any key to close")
Console.ReadKey()
End Try
End Sub
End Module
Well, appearently problem was about TLS version mismatch. All Salesforce sandboxes refuse TLS 1.0 connections. Our vb.net test code was using TLS 1.0 thus returning an error. It would be great if Salesforce would return better error code.
All I needed to do was add a line of code on top of the code block:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11