I have many API calls to the server, in many of them if I get a 401 response then I should forward the user to the login screen to refresh the token that I used for authorization.
http.post(
URL,
body: jsonEncode(loginHttpBody),)
.then((response) {
if (response.statusCode == 401) {
Navigator.pushNamed(context, LoginScreen.id);
}
});
I need a way to make a global interceptor to check if any of the HTTP requests have 401 status to forward the user to log in screen, not writing this code in all of my HTTP requests.
The package that I use for my HTTP request is http
Related
This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 1 year ago.
This has been marked as a duplicate which is NOT true. This is a mobile app, NOT a web app. There is no originating domain, like the proposed answer has for a web app.
I am trying to use the salesforce api with flutter / dart. I get the following error:
Access to XMLHttpRequest at 'https://instancename.my.salesforce.com/services/data/' from origin 'http://localhost:53765' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
It does not matter if I try to get a session token
void getData() async{
var headers = {
'Authorization': 'Bearer access_token',
};
var res = await http.get('https://instancename.my.salesforce.com/services/data/v20.0/', headers: headers);
if (res.statusCode != 200) throw Exception('http.get error: statusCode= ${res.statusCode}');
print(res.body);
}
or just the version
void getData() async{
Response response=await get("https://instancename.my.salesforce.com/services/data/");
print(response.body);
}
everything fails.
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources. ... For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts.
you have to set cars policy to your web server not flutter application it happen when you want to connect to you web api on internet if you run your web api on local you'r not get that error
I am trying to do something along these lines to make an authenticated api request:
Future<http.Response> fetchAlbum() {
return http.get(
'https://jsonplaceholder.typicode.com/albums/1',
// Send authorization headers to the backend.
headers: {HttpHeaders.authorizationHeader: "Basic your_api_token_here"},
);
}
I get my api tokens by calling
FirebaseUser user = FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password).
My questions are:
Don't these tokens expire after a short period of time? How do I make it so my user doesn't have to constantly log in? I don't understand this at all.
Should I save my user variable in a global provider state and access it this way?
I've been watching tons of tutorials on this and I don't get it.
I'm building a React app and Express API with a "Sign in with LinkedIn" feature. I've got my OAuth sorted, so I have an access token now but I keep getting a CORS issue when I try using it to fetch data. Can I make REST API requests directly from my React app (client side)? Or do I need to proxy every request through my own Express server / API?
useEffect(() => {
// get linkedin data
fetch(`https://api.linkedin.com/v2/me`, {
method: 'get',
mode: 'cors',
headers: {
'Connection': 'Keep-Alive',
'Authorization': `Bearer ${accessToken}`
},
}).then(response => response.json()).then(function(data) {
console.log(data);
});
}, []);
Access to fetch at 'https://api.linkedin.com/v2/me' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
In API they call without Authorization is fine.
How to set header for it?
"thanks"
let headers: Headers = new Headers({ 'Authorization': token, 'Content-Type': 'application/json; charset=UTF-8' });`
let options: RequestOptions = new RequestOptions({headers: headers});
let params: URLSearchParams = new URLSearchParams();
params.append('latitude', '23.259933');
params.append('longitude', '77.412615');
params.append('nearby', '5');
return this.http.post(baseUrl, params, options)
.map(
(response: Response)=>{
return response;
}
)
Chrome console:
Response for preflight has invalid HTTP status code 404
This happens because the browser sends the headers of your request to the server before sending the actual request (what is called preflight) so as to verify your request complies with the CORS policy that is defined in the server's configuration.
So what you need to do is double check that the server you are contacting is configured properly to accept the request as you make it.
Make sure that your backend server is accepting not only the POST request but also an OPTIONS request for the same endpoint url. The OPTIONS request should just return with the success 200 code.
On that server you probably have something like "when a user hits endpoint /abc with request type POST, then return some data". You also need something that says "when a user hits endpoint /abc with request type OPTIONS return 200 OK"
If all else fails you could try using this plugin in your browser, but keep in mind this will help only continuing development and is a band-aid solution that won't work in production of course.
I'm developing a small react node application with JWT passport for authentication. I've tested all the endpoint through postman(by passing token with authorization header) and they are working properly.
This is the call im making from the front-end
export const getUsersDetails=()=>{
console.log( localStorage.getItem('jwtToken'));
return (dispatch) => {
return axios.get('http://localhost:3030/users',
{ headers: { 'Authorization': localStorage.getItem('jwtToken') } }
).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
I have enable CORS by using the the CORS module. this is the how the network calls looks like from the browser
the authorization header looks like
authorization:[object Object], eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Should this be like authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Is this the reason why im facing this issue? How to overcome this?
I was able to solve a similar issue on a MERN stack, by configuring axios globally in the react application, by adding Bearer and one space, in front of the token that is assigned globally.
axios.defaults.headers.common['Authorization'] =Bearer ${token};
initially, it was without Bearer and i kept getting a 401 status code.
axios.defaults.headers.common['Authorization'] = token;
When you want authorization in your app, it depends on how you have done your back end. If everything is ok trough postman, show how your headers in postman look when you have tasted. I use xsrf token and here is how my request header look:
{headers:
{"Access-Control-Allow-Headers" : "*",
"X-XSRF-TOKEN": this.$cookie.get('XSRF-TOKEN')}
}
Maybe you should just put "Access-Control-Allow-Headers" : "*"