-1
Summary : When I Make Backend Requests with Postman all goes well, but when I make requests with Front-End Reactjs Axios 2 requests come to the API, 1 without Token and the other with Token.
I am in a project consisting of a Java API (JAX-RS - JERSEY2) that is consumed by a REACTJS application (Axios implementing Xmlhttprequest).
When the Front-End makes a Request for the API in certain End-Points it is necessary to use the Token in the Request Header.
Follow the API Filter code:
@Provider()
@Priority(Priorities.AUTHENTICATION)
public class Authentication implements ContainerRequestFilter {
@Context
private UriInfo uriInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
JWTController jwt_controller = new JWTController();
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
System.out.println(authorizationHeader == null);
}
}
Requests made with POSTMAN returns :
> false
Requests made with AXIOS returns :
> true
> false
Follows Javascript code that makes the requests:
Archive that stores Axios services/api Instances:
import Axios from 'axios';
export const api = Axios.create(//Instacia para requisições sem Token
{
baseURL:"http://localhost:8080/beta_projects"
}
);
export const api_with_token = Axios.create(//Instacia para requisições com Token
{
baseURL:"http://localhost:8080/beta_projects"
}
);
pages/home.js file:
try {
let token = localStorage.getItem("token");
let id_user = getIdUser(token);
let URL = `user/${id_user}/activities`;
api_with_token.defaults.headers.common['Authorization'] = `Bearer ${token}`;
let response = await api_with_token.get(URL);
this.setState({ activities: response.data });
console.log(response.data);
return response;
} catch (err) {
console.log(err.response);
return err;
}
I don’t understand why the two requests.
[RESOLUTION] Open the authentication filter for OPTIONS type requests as follows
if (isPublic() || requestContext.getMethod().equals("OPTIONS")) {
return;
}
take a look at the browser’s network tab and see the requests, I think it’s very likely that the first request is a call of options
– Lucas Miranda
Yes, I’m doing a GET on the API, and the first one is the OPTIONS type. Apparently it’s there bringing information from the API.. But how could I filter it?
– Gustavo de Carvalho Reinaldi
The Source I’m looking for is of the GET type, but it sends this PREFLIGHT Request of the OPTIONS type and it returns with the 401 status.
– Gustavo de Carvalho Reinaldi
there is no way to escape much of this since whenever a request is sent "not simple" this options will be sent before, what you can do maybe would be to release the request options in the Cors config of your backend
– Lucas Miranda