Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Receive MethodNotAllowed in v107 #1707

Closed
dcdraper opened this issue Jan 17, 2022 · 13 comments
Closed

Receive MethodNotAllowed in v107 #1707

dcdraper opened this issue Jan 17, 2022 · 13 comments
Labels

Comments

@dcdraper
Copy link

dcdraper commented Jan 17, 2022

I am attempting a POST request in v107 that used to work before v107. See https://stackoverflow.com/questions/70686539/v107-getting-status-code-of-methodnotallowed-on-a-post-request-that-used-to-work for details. As suggested by Alexey there I have re-written some code and now I get an exception with MethodNotAllowed, rather than a response with status - MethodNotAllowed.

To Reproduce
Reworked Code:

//constructor
public MerlinServiceBase()
{
    GetCreds();
    _authClient = new RestClient(_authUrl);
    _authClient.Authenticator = new HttpBasicAuthenticator(_authClientId, _authClientSecret);
}

private async System.Threading.Tasks.Task<string> GetAuthTokenAsync()
{
     var request = new RestRequest().AddParameter("grant_type", "client_credentials");
     var response = await _authClient.PostAsync<Dictionary<string, string>>(request);
     return response["access_token"];
}

Expected behavior
I expected to get an auth token

Stack trace

System.Net.Http.HttpRequestException
  HResult=0x80131500
  Message=Request failed with status code MethodNotAllowed
  Source=RestSharp
  StackTrace:
   at RestSharp.RestClientExtensions.<PostAsync>d__11`1.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at RentalWebClient.V3.QA.Automation.UI.MerlinServiceBase.<GetAuthTokenAsync>d__10.MoveNext() in C:\Source\OpenTech\Kiosk\Ota.Kiosk.RentalWebClient.V3.QA.Automation\RentalWebClient.V3.QA.Automation.UI\_Merlin API\Merlin_ServiceBase.cs:line 87

  This exception was originally thrown at this call stack:
    [External Code]
    RentalWebClient.V3.QA.Automation.UI.MerlinServiceBase.GetAuthTokenAsync() in Merlin_ServiceBase.cs

Desktop (please complete the following information):

  • OS: Windows 10
  • .NET Framework 4.7.2

Additional context
Please let me know what other details I could add.

@dcdraper dcdraper added the bug label Jan 17, 2022
@alexeyzimarev
Copy link
Member

In my SO answer I suggested tracing the request so you can understand why you get this response. It is not RestSharp that returns the "method not allowed response", it is the server. It is only possible to find what the issue is if you can compare the actual request made by RS 107 and a working request. In my answer, I admitted that I don't see obvious issues in the code, and I suggested some improvements, but I wasn't really expecting it to work, honestly.

@alexeyzimarev
Copy link
Member

MDN also suggests:

The server must generate an Allow header field in a 405 status code response. The field must contain a list of methods that the target resource currently supports.

Response headers are available if you use ExecutePostAsync<T> as part of RestResponse. If you inspect the Allow header value returned by the server, you can understand the reason for error better,

@alexeyzimarev
Copy link
Member

Btw, I think you are trying to get the access token from an OAuth2 authorisation server. It's irrelevant for the issue, but it could be easier to deserialize the response to a proper object instead of using the dictionary. The response format is well-known:

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
 
{
  "access_token":"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3",
  "token_type":"Bearer",
  "expires_in":3600,
  "refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk",
  "scope":"create"
}

@alexeyzimarev alexeyzimarev added the awaiting-info Not enough information provided label Jan 18, 2022
@dcdraper
Copy link
Author

The Allow Header said Get, but that is not how I did it before, it was always Post. When I try Get I get a Bad Request response.

Do you have a working example for 107 with OAuth2? I am totally stuck here without being to auth first. I wish I had time at work to figure out how to use that tracer but I do not at the moment.

This RestSharp update is going to require lots of changes to our automation projects and I really just need to stay on the lower version for now until I can find help.

@alexeyzimarev
Copy link
Member

alexeyzimarev commented Jan 18, 2022

An example for OAuth2 would be problematic as most of the vendors use their own deviations. Unlike OAuth1, which is very strict, OAuth2 is quite relaxed in terms of what headers are used, etc.

Do you have any docs of the server you are trying to call? Can you post it here? Maybe that can help.

Staying on v106 for a while is a decent option. There's no immediate need for migration unless you face any of the issues fixed by v107. Still, in many cases I see people posting "working code" for v106, which is obviously wrong, but it worked because of some bugs embedded in the library and became "features"... It doesn't apply to your code, don't get me wrong please, I don't see any obvious issues there. But without much information about what the server actually wants, it's hard to diagnose the issue.

@alexeyzimarev alexeyzimarev removed the awaiting-info Not enough information provided label Jan 18, 2022
@dcdraper
Copy link
Author

We use Amazon Cognito with client_credentials: https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html

I am still trying stuff here and there, learning about and finding my way around the the new and old layouts of the client and response objects. A minor thing I noticed is that Resource is set to "" instead of null on the new RestRequest object, but moving "/token" to there from my base url seemed to not help (or hurt) at all.

@alexeyzimarev
Copy link
Member

alexeyzimarev commented Jan 18, 2022

I created a simple Twitter client with a custom authenticator. It appears that Twitter OAuth2 token endpoint works the same way as the one you're using. I had no issues with it.

https://gist.github.com/alexeyzimarev/62d77bb25d7aa5bb4b9685461f8aabdd

I added those tracing handlers just so I can observe the request. It didn't work the first time because I used wrong credentials.

@dcdraper
Copy link
Author

dcdraper commented Jan 18, 2022

Thanks!
I will try the example but I cannot use the C# version you are using in my projects since we require .NET Framework not Core. Where can I get RestSharp.Tests.External.Tools?

I assume HttpTracer comes from the HttpTracer 2.1.1 nuget package?

@alexeyzimarev
Copy link
Member

The snippet doesn't work with Cognito, I tried. I have no idea why. The only way to find out is to inspect the full request content in a working version and the not-working version. I am sorry but I spent a couple of hours yesterday on this already.

The Tools namespace contains the OutputLogger. You don't need it.

@alexeyzimarev
Copy link
Member

alexeyzimarev commented Jan 19, 2022

Btw it is easy to compare requests using a tool like https://requestbin.com.

Here, for example, is the request made with RS 107 using the authoriser I've built:

image

To me, it looks completely legit. I am not sure what Cognito is unhappy about.

@alexeyzimarev
Copy link
Member

Same using your code from SO for RS 106

image

@alexeyzimarev
Copy link
Member

Basically, Cognito is picky about Accept content types. The code below fixes it:

        using var client = new RestClient(options) {
            Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret),
            AcceptedContentTypes = new []{"application/json", "text/json", "text/x-json", "text/javascript"}
        };

I am looking to improving the Accept header content.

@dcdraper
Copy link
Author

That fixed it :)
Thank you so much for spending so much of your valuable time on it, it is appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants