There is an api for authorization, I send a request using thunder client, everything seems to be ok, I get a token in response, but when I try to knock on the same link in the application itself using the dio library, I get an Http status error [301] in response, what could be the problem, I didn't really find an answer anywhere?
how do I send a request
final response = await _dio.post(
'http://someaddress.com/api/auth/login',
data: {"login": phone, "password": event.password},
);
Error:
Http 301 status code means that the link is not anymore available and new one is defined in Location header. The response looks like something like this.
HTTP/1.1 301 Moved Permanently
Location: https://foo.bar/foobar
Response headers in dio can be accessed by headers property.
Related
My task is to call the link in web using flutter through the GET method and get the html which in the future I want to show on the same page where I am.
Here is an example:
final response = await http.get('SOME URL',
headers: {'Access-Control-Allow-Origin': '*'});
if (response.statusCode == 200) {
print("200: Try to get HTML");
// TODO get HTML from response
return jsonDecode(response.body).toString();
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
The problem is that when I initialize the page, I call this link, but the browser blocks and does not allow calling
Error example:
Access to XMLHttpRequest at 'URL' from origin 'http://localhost:55827' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
As far as I could figure it out, the problem is that I call some other link on the localhost and because of this the CORS blocks.
I could not find a solution to this problem. Please help me how, during initialization, could I call the GET method with url and take html from the response ?
You need to allow cross origin request in the backend page you are using, not in http header. The command if different depending on the language you are using i.e. php, node js, python etc. for your backend.
Like if you are using PHP then you have to specify this header -
header('Access-Control-Allow-Origin: *');
I don't know if it ever would, but if my server responded with HTTP status code 304, would the Fetch API (specifically response.ok) and axios.get() see the response as 200?
The documentation for both talk about the request being viewed as successful if the response code is in the range 200-299, but clearly 304 is outside this.
When a browser does a GET request with a If-Match or If-Modified-Since header, and the server responds with 304 Not Modified, the client will just see this as 200 OK.
The response is served from cache, instead of the server, and it allows the client (axios in your case) to not have to understand HTTP caching, but it can still take advantage of it.
I don't know what a client will do when they send a request without preconditions and still get a 304 response. A client wouldn't have an earlier cached response so this would definitely be 'broken'. I'd imagine you'd get an error but I'd be curious to see what.
No, they will both not see the response as 200.
While axios.get will return a promise rejection, the return value of response.ok when using fetch API will be false and response.redirected will be true.
I run the exact same code on Android and Web by using Dio for sending requests and what I see is that my backend doesn't get my custom added headers when I send the request from browser, but everything works fine if I do the same from emulator.
CORS is correctly setup on my backend.
Dio dio = Dio();
dio.options.headers[HttpHeaders.authorizationHeader] = "Bearer $token";
final Response response = await dio.get("http://$host:$port/$path", queryParameters: {"searchText": searchQuery, "page": 0, "pageSize": 100});
Additional information
post request works fine, the header is only missing from get requests. Either I use the http or dio packages.
However I can see in my server logs the following line when I log out all the headers of the request:
headerName: access-control-request-headers
header: authorization
Has anyone seen something similar?
As it seems I had to enable cors in spring security separatelly.
httpSecurity.csrf().disable()
.cors().and()
.authorizeRequests()
.antMatchers("/api/admin/**").hasRole("ADMIN")
.antMatchers("/api/support/**").hasRole("SUPPORT")
.antMatchers("/**").permitAll()
.and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter::class.java)
Once I did so everything started to work.
So to sum up,
I used my custom headers in other places those were handled by my global CorsFilter but headers related to spring-security like Authorization are handled by spring-security so cors has to be enabled there as well regardles if I added Authorization to my global CorsFilter or not.
I'm trying to pass digest auth on my ip camera
I do it on Flutter but actually it doesn't matter.
I got http response from camera with status code 401 Not Authorized
and Headers:
{content-type: text/html, pragma: no-cache, cache-control: no-cache, www-authenticate: Digest
realm="goAhead", domain=":13237",qop="auth", nonce="a98326cc6022c2a2b7cc7e57a5956f77",
opaque="5ccc069c403ebaf9f0171e9517f40e41",algorithm="MD5", stale="FALSE", date: Thu Dec 26 16:31:43
2019, server: GoAhead-Webs}
from this source here I've found the needed Response constructor view like this:
var mResponse = "Digest username=\"$username\", realm=\"$realm\", nonce=\"$nonce\", uri=\"$uri\",
response=\"$_response\", cnonce=\"$cnonce\", nc=$nc, qop=\"$qop\"";
I create this:
Digest username="admin", realm="goAhead", nonce="a98326cc6022c2a2b7cc7e57a5956f77",
uri="/onvif/device_service", response="5313fe5265efcd3da37cec322d92ebd7", cnonce="1234567890",
nc=00000001, qop="auth"
and send http request to camera:
Future<http.Response> new_response = http.post(snapshotUrl, headers: {"Content-Type":"text/xml; charset=utf-8", "Authorization": mResponse }, body: mGetSnapshotUriAuth);
new_response.then((resp){
print(resp.statusCode);
});
and getting this error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Invalid header field name
When I remove "Authorization" field of headers, camera response with 401 code.
I'm trying to get snapshot from ip camera works on Onvif protocol. I am not sure in Uri parameter.
The same error when I try send this http request via http Client on desktop machine screenshot
Question 2:
When I try to change uri param to something else e.g:
String uri = http://www.onvif.org/ver10/media/wsdl/GetSnapshotUri";
My camera stops reply to me. The same behaviour I can see when I start use Http sniffer or change Digest's response's field name. Sometimes reset camera helps(or even hard reset) and it start working(return 401 error) again, sometimes it's start working by itself. But by the way the camera continues working via others Camera Viewer Apps.
My screenshot from http sniffer
PS After many tests to solve this problem I think my param values are correct, because If change something e.g username, password and etc (except cnonce. When I change сnonce the result the same), I got other error: 401.
screenshot of Android studio with error
Writing SOAP requests by hand is BAD PRACTICE. I know nothing about dart, but I invite you to look for a tool like gsoap for generating the functions from thw WSDL files you can find here.
Don't write requests by hand, you'll end up in a mess when parsing the responses.
I was trying to setup Jmeter for Salesforce API testing. However getting the below error during Salesforce authorization:
"error":"unsupported_grant_type","error_description":"grant type not
supported"
I am passing the parameters as in the screenshots attached. The same parameters when passed in Postman works fine, however I am getting this error in Jmeter. Please let me know if I am making some error in passing the parameters in Jmeter.
Jmeter_HTTP Header Manager
Jmeter_HTTP Request
Jmeter_Sampler Result
According to HTTP Status Code 400 documentation
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
Looking into your request, you're sending Content-Type header as application/json therefore your server expects JSON and you're providing something different.
My expectation is that you should switch to Body Data tab of the HTTP Request sampler and set the request body to look like:
Check out REST API Testing - How to Do it Right article for more information on REST APIs testing using JMeter.
I struggle with the same issue but it finally worked for me by doing the following:
Use Content-Type application/x-www-form-urlencoded in an HTTP Header Manager
Make sure is a POST Method and that you're using https
Not sure if it is necessary but in the Parameters tab make sure all (grant_type, password, client_secret_ client_id and username) are Content-Type application/x-www-form-urlencoded and check the URL Encode option for all
Only check "Follow Redirects" and "Use KeepAlive" options in the HTTP Request
hope it works for you too