RestSharp RestClient.Execute errors Bad Gateway - but works if I step through the code - restsharp

Background
an existing VB.NET application has been working for 5+ years, recently started to error when POST data to an API
Async Function Post(body, path) As Task(Of RestResponse)
Dim request = New RestRequest(path, Method.Post)
request.AddJsonBody(body, "application/json")
Dim client As RestClient = New RestClient(psURL)
client.UseNewtonsoftJson()
Dim response As RestResponse = Await client.PostAsync(request)
PostREST = response
End Function
When I debug the application, and add a breakpoint on the
Dim response As RestResponse = client.Execute(request) line, then it works as expected.
Note: I've upgraded to v108.0.1.0 and getting the same error

Related

SSRS Sql Server Reporting Server Custom Security 2019 exception in Windows Server 2019

I am facing problem with respect to SSRS(Sql Server Reporting Server) 2019 Custom security Exception in windows server 2019,
Getting error as sqlAuthCookie is null, sending WebRequest to Reportserver to generate sqlAuthCookie from VB.net code but server unable to generate Cookie.
Anything solution/help would be much appreciated
Tried sending request from Vb.net to SSRS windows server 2019
Getting Custom security exception error and sqlAuthCookie error also
VB.NET Code
Protected Overrides Function GetWebResponse(ByVal request As WebRequest) As WebResponse
Dim response As WebResponse = MyBase.GetWebResponse(request)
Dim cookieName As String = response.Headers("RSAuthenticationHeader")
' If the response contains an auth header, store the cookie
If Not (cookieName Is Nothing) Then
Dim webResponse As HttpWebResponse = CType(response, HttpWebResponse)
Dim authCookie As Cookie = webResponse.Cookies(cookieName)
' If the auth cookie is null, throw an exception
If authCookie Is Nothing Then
Throw New Exception("Unable to generate report - the Reporting Services Custom Security Extension is expected to be enabled in XB")
End If
' otherwise save it for this request
Me.AuthCookie = authCookie
' and send it to the client
End If
Return response
End Function
SSRS service code
//adding new GetUserInfo method for IAuthenticationExtension2
public void GetUserInfo(IRSRequestContext requestContext, out IIdentity userIdentity, out IntPtr userId)
{
userIdentity = null;
if (requestContext.User != null)
{
userIdentity = requestContext.User;
}
// initialize a pointer to the current user id to zero
userId = IntPtr.Zero;
}

Use RestSharp to get MS Graph token

I am new to using MS Graph and the new version of RestSharp. I put together a simple console app in VB.NET to learn the process. Have spent way too much time looking at solutions on the internet, but not getting the answers I want. The ultimate goal is to upload files to a OneDrive account autonomously.
So I created an App registration on Azure for this app. Then to test I created a console app to test how the process works. I am using the latest version of RestSharp which is very different from the version I was using. The console app calls a simple subroutine shown below to get the token to make calls to Graph. When I run I get the errors: "System.Net.ProtocolViolationException' in System.dll" and "System.Net.ProtocolViolationException' in mscorlib.dll". Code follows:
Dim client As New RestClient("https://login.microsoftonline.com/f8cde-----/oauth2/v2.0/token")
Dim request As New RestRequest(Method.Post)
request.AddHeader("Content-Type", "application/x-www-form-urlencoded")
request.AddHeader("Host", "login.microsoftonline.com")
Dim body As String = "client_id=8e4---------" &
"scope=api://8e4da056-8425-4-.default" &
"client_secret=Piy7Q~7----------" &
"grant_type=client_credentials"
request.AddBody(body)
Dim response As RestSharp.RestResponse = Await client.ExecuteAsync(request)
Console.Write(response.Content.ToString)
Console.ReadKey()
End Sub
I admit I really don't know what I am doing here, but want to learn.
I can suggest spending time reading the documentation. RestSharp forms the request correctly if you use the RestRequest API to build the request.
Here is what you need to do:
Dim options = New RestClientOptions("https://login.microsoftonline.com/f8cde-----/oauth2/v2.0/token")
options.BaseHost = "login.microsoftonline.com"
Dim client = New RestClient(options)
Dim request As New RestRequest(Method.Post)
request.AddParameter("client_id", "8e4---------")
request.AddParameter("client_secret", "Piy7Q~7----------")
request.AddParameter("grant_type", "client_credentials")
Dim response = Await client.ExecuteAsync(request)

I am getting error for RestSharp library for C# .NET unable to return request, IRestResponse is deprecated

I am getting error at the last line since RestSharp has made major breaking changes in their latest release. my methods are failing???
public RestResponse SendRequest(string url, object requestBody)
{
var client = new RestClient(baseURL + url);
var request = new RestRequest();
request.Method = Method.Post;
request.AddJsonBody(requestBody);
return client.ExecuteAsync(request); <= this is the line throwing error message.
Error CS0029 Cannot implicitly convert type
'System.Threading.Tasks.Task<RestSharp.RestResponse>' to
'RestSharp.RestResponse'
this last line is where I am getting error from RestSharp library. Any help is appreciated. The old implementation used to work. Now It started failing after updating to the new RestSharp version.
here is the new documentation
https://restsharp.dev/v107/#making-requests
var client = new RestClient(baseURL + url);
var request = new RestRequest();
request.Method = Method.Post;
request.AddJsonBody(requestBody);
return client.ExecuteAsync(request).Result;
As per RestSharp this should be the NEW implementation.....

Getting Error 400 when using Authentication Broker in Win 8 App for Stackexchange API

I'm trying to connect to StackExchange API using OAuth.
So far i've been able to get a token and retrive data that does not require authentication.
When i try do query that uses the authentication, i'm getting error 400 - Bad request.
Heres the code:
Dim Key As String = "(app_key)"
Dim RequestURL As String = "https://api.stackexchange.com/2.2/me/questions?access_token=" & Token & "key=" & Key & "&order=desc&sort=activity&site=stackapps"
Dim Handler As HttpClientHandler = New HttpClientHandler()
If Handler.SupportsAutomaticDecompression Then
Handler.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
End If
Dim HttpClient As HttpClient = New HttpClient(Handler)
Dim query = Await HttpClient.GetAsync(RequestURL)
If query.IsSuccessStatusCode = True Then
'(query.Content.ReadAsStringAsync())
End If
Tried using only key, only access token, or none in the request, but received the same error. Also tried adding "OAuth" header and "access_token":
HttpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("OAuth", Token)
HttpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("access_token", Token)
Any help appreciated.
Solved it! Turns out a was using the wrong key. I managed to make it work by using both access_token and key in the RequestUrl, not using the request headers.

Can't get a token from the Google API

I'm trying to exchange my authorization code for a token with the Google OAuth2 API for my Windows 8 app, but I keep getting HTTP 400 errors.
This is how I perform the request (simplified):
var url = "https://accounts.google.com/o/oauth2/token";
var body = "code=4/LEXF1iAVRZvfCfdQg9r1aFqoYDgV&client_id=904019870963.apps.googleusercontent.com&client_secret=[removed]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code";
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), new StringContent(body));
response.EnsureSuccessStatusCode();
Visual Studio usually simply gives me a HTTP 400 bad request error, when I try the same thing in Fiddler I also get an HTTP 400 error, but with this as content:
21
{
"error" : "invalid_request"
}
0
I read all the documentation about Google OAuth, I searched on Google and StackOverflow for this issue, I tried changing all different sorts of things in my code (UrlEncode, etc.), I used the Google API Playground to see what kind of requests it performs and compared it with my own requests (couldn't find a difference except for the return URL, the auth code and the user-agent). No matter what I do, I just can't get this working, I've been stuck for hours already.
Can anyone help me out here?
Read the body content to get the error json you noticed in Fiddler.
HttpClient httpClient = new HttpClient();
var response = httpClient.PostAsync(new Uri(url), new StringContent(body)).Result;
var content = response.Content.ReadAsStringAsync().Result;
content now holds :
{
"error" : "invalid_request"
}
You could project the error in an object, by specifing your error type like: response.Content.ReadAsAsync().Result
For the invalid request part, you should play with UrlEncode. I know you say you tried it, but applying it at the right spots really solves your problem.
var body = "code="+WebUtility.UrlEncode("4/LEXF1iAVRZvfCfdQg9r1aFqoYDgV")+
"&redirect_uri="+WebUtility.UrlEncode("https://yoursite...")+
"&client_id=904019870963.apps.googleusercontent.com" +
"&scope=" +
"&client_secret=********" +
"&grant_type=authorization_code";
HttpClient httpClient = new HttpClient();
var response = httpClient.PostAsync(new Uri(endpoint),
new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
This is the code that works for me. Should work for you also.