I'm trying to use the AsyncOAuth2Client client to authenticate requests:
async def get_oauth_client():
client = AsyncOAuth2Client(os.environ['OAUTH_CLIENT_ID'],
os.environ['OAUTH_CLIENT_SECRET'],
scope='my_scope',
grant_type='client_credentials',
token_endpoint=os.environ['OAUTH_TOKEN_URL'],
timeout=3600)
await client.fetch_token(os.environ['OAUTH_TOKEN_URL'])
return client
and then subsequently use the client to make a request:
async def make_request(method, data, headers):
client = await get_oauth_client()
await client.ensure_active_token()
method = getattr(client, method)
response = await method(url, data=data, headers=headers)
client.close()
return response
however, when calling the above method I keep getting a 401 back: <Response [401 Unauthorized]>, despite the fact that when I look at the expires_at on the token there is still plenty of time left for it:
{'access_token': 'some_token',
'expires_in': 3600,
'token_type': 'Bearer',
'expires_at': 1600388963} # now + 1hr utc
It may be relevant that I initially tried this same method with success yesterday, setting the timeout=None and it worked. However, when trying the same code today I hit these failures.
Related
I have an issue with RestClient response is coming back as
"StatusCode: 0, Content-Type: , Content-Length: )"
with the ErrorMessage of
"The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing."
Is this a timeout on the url's end or my httpclient? Is request.timeout correct? It might take 5+ minutes for this request even though it's only 170KB of data due to their end being poorly optimized.
var client = new RestClient(url);
RestRequest request = new RestRequest() { Method = Method.Get };
request.Timeout = 300000;
request.AddParameter("access_token", AccessToken);
request.AddParameter("start_date", StartDate.ToString("yyyy-MM-dd"));
request.AddParameter("end_date", EndDate.ToString("yyyy-MM-dd"));
request.AddParameter("offset", offset.ToString());
var response = await client.ExecuteAsync(request);
var responseWorkLoads = JObject.Parse(response.Content).SelectToken("worklogs");
There are two timeouts that RestSharp allows you to set.
When you create a new instance of RestClient, you can specify the HttpClient timeout that will override the default 100 ms using RestOptions:
var client = new RestClient(new RestClientOptions { Timeout = 300000 });
As the wrapped HttpClient is instantiated and configured once per RestClient instance, setting the request timeout doesn't override that setting, otherwise the client won't be thread-safe.
The request timeout, on the other hand, overrides the client timeout if it is less than the client timeout. RestSharp creates a cancellation token source using the request timeout, so the request will be cancelled when the linked cancellation token cancels.
I believe that currently RestClient also doesn't set the failure reason properly when the client times out, only if the token gets cancelled. I will create an issue for that.
I am new to rest assured, I want to perform some get and post for test data generation using rest assured. But I am unable to get the LTPA token and pass them to post. This works with postman but I want to do it through java. Any help
final String uri = "https://XXXX/Rest/XXXXX?user=XXXXX&pass=XXXX";
final Response response = RestAssured.given().relaxedHTTPSValidation().accept(ContentType.JSON).get(uri);
System.out.println(response.prettyPrint());
Map<String, String> allCookies = response.cookies();
System.out.println(allCookies);
Output
{JSESSIONID=XXXXXXX:-1}
but i do not see the LTPA2 token
Your LTPA2 token must be in Response headers.
You can get the response headers by
response.headers ();
In case if LTPA token is also not available in headers then share the screenshot of postman so I can help you out.
I have this simple dart snippet:
import 'package:http/http.dart' as http;
Client _http = new BrowserClient();
final response = await _http
.post(url, headers: someHeader, body: someValue);
The server for the current request, returns Bad Request 400 response. I want to be able to get the status code for some reasons. But as soon as the _http.post get called, I get this error:
POST http://localhost/path 400 (Bad Request)
Putting the block in try/catch doesn't help, since the exception catched is ClientException which has no information about status-code and response-body (which is important here). How can I handle status-codes here, without throwing exceptions?
UPDATE:
I have this snippet after _http.post() call:
if (response.statusCode == 400) {
// manage bad request
}
But the response is null, so the statusCode is not accessible here.
UPDATE 2:
I get the request on server and can trace on server. As I mentioned, the server is sending a 400 Bad Request response, and works just fine. But getting the response in Dart causes the error.
The Response object has a field statusCode where you can get the status code of the response.
You can do something like that:
final response = await _http
.post(url, headers: someHeader, body: someValue);
if (response.statusCode == 400) {
// manage bad request
}
I suspect the url, a header or the body is invalid somehow. (e.g. invalid characters in a header). The request is not actually being sent to the server, and so ClientException is being thrown instead of giving you a response.
I am working with an API that wants me to send the token along with Header, specifically Content Header.
Here is my code block.
string path_current_user = "me";
var cookie = HttpContext.Request.Cookies.Get("cookietoken");
string cookie_with_token = "ACCESS_TOKEN="+cookie.Value+";";
client.DefaultRequestHeaders.Add("Cookie", cookie_with_token);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
HttpResponseMessage response = await client.GetAsync(path_current_user);
I always get a 410 Unauthorized response. However, during debugging I can collect the values from the client object, and copy paste them into https://www.hurl.it, and I get the expected 200 OK response. So, I know the values that are being stored in the above code are correct. Its not a credentials issue for sure.
I have looked at almost 50 different threads on stack overflow, but none of them talk about this specification situation. Doing a GET with the Header Content set. Here is a screenshot of the HURL that works just fine.
Update 1 - Here is the API documentation for what I am trying to achieve.
Endpoint
GET me
Request Route
GET me
Headers
Content-Type: application/json Cookie: ACCESS_TOKEN="token characters
come here and remove the quotes"; Host: x.x
Update 2 - One of my mentors, recommended the following.
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://small-project-api.herokuapp.com/me");
request.Headers.Add.("Content-Type", "application/json");
request.Headers.Add.("Cookie", cookie_with_token);
var response2 = await httpClient.SendAsync(request);
var responsestring = await response2.Content.ReadAsStringAsync();
}
He is of the opinion that may be such a request, as mentioned below, simply won't work in dot net. I am all but ready to give up here.
I tried to send a bearer token to an Auth0 API using Postman and it works perfectly.
I then tried the same using RestSharp (in c#) but it doesn't work at all.
Below is my code. I've tried many different formats but none of them work.. Is there any other way I can try to make it work?
var client = new RestClient("http://domain.auth0.com/api/v2/users");
RestRequest request = new RestRequest(Method.GET);
//request.AddHeader("authorization", "Bearer eyJhbGcJ9.eyJhdWQiOiJ6VU4hVWUE2.token");
//request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddHeader("Accept", "application/json");
//RestClient client = new RestClient("http://domain.auth0.com");
//RestRequest request = new RestRequest("api/v2/users", Method.GET);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("Authorization",
string.Format("Bearer " + "eyJhbGciOI1NiIsI9.eyJhdWQiOiWmVhTWpD2VycyI6eyJhY.token"),
ParameterType.HttpHeader);
//request.AddParameter("Authorization",
// String.Format("Bearer {0}", token),
//ParameterType.HttpHeader);
var response = client.Execute(request);
PS: the token was changed.
The problem is that you're using an HTTP URL. When you issue the first request the token is included, but you receive a redirect response informing that you should be calling the HTTPS endpoint.
Since RestSharp will not include the token in the second request performed automatically due to the first redirect response you get an unauthorized response.
You need to update the URL to be HTTPS which will prevent the redirect and as a consequence solve your problem. If you want to make multiple authenticated request using the same client you also change your code to be:
using RestSharp;
using RestSharp.Authenticators;
class Program
{
static void Main(string[] args)
{
// Use the HTTPS scheme
var client = new RestClient("https://[domain].auth0.com/api/v2/users");
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
"eyJhbGciJIUz.eyJhdWQi4QW5OXhCNTNlNDdjIn0.vnzGPiWA", // Update the token
"Bearer");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine("{0}", response.StatusCode);
}
}
If you really need to handle redirects and still send the token, check: https://github.com/restsharp/RestSharp/issues/414