I've been trying to build relatively simple app with angular and jersey REST on the back end. I've managed to make some communication between the two but when I try to implement security as by following this answer Best practice for REST token-based authentication with JAX-RS and Jersey I get some strange behaviour.
When I try to make a POST request from Angular app (localhost:4200) I get 403 Forbidden (Response to preflight request doesn't pass access control check) without even executing ContainerRequestFilter or ContainerResponseFilter.
When I send exactly the same request with POSTMAN everything works fine. Every filter gets called and authentication works fine.
Here are my classes:
@Provider
public class CorsFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request,
ContainerResponseContext response) throws IOException {
System.out.println("cors");
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
System.out.println(response.getHeaders());
}
REST
@Path("/like")
@POST
@Secured({User.RoleEnum.ADMIN,User.RoleEnum.MODERATOR,User.RoleEnum.SUBSCRIBER})
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response like(Comment toUpdate){
System.out.println("like");
Comment updated = null;
try {
updated = commentService.like(toUpdate);
} catch (IOException e) {
// TODO Auto-generated catch block
return Response
.serverError()
.build();
}
if(updated !=null){
return Response
.ok(updated)
.build();
}
return Response
.noContent()
.build();
}
@Secure interface, AuthorizationFilter and AuthenticationFilter are basically the same as the link I posted above.
Angular request
const headersAuth = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.userService.loggedUserToken});
return this.http.post(this.url + this.likeURL, comment, {headers: headersAuth})
.map(
(res: Response) => {
const body: CommentModel = res.json();
return body || {};
}
)
.catch(this.handleError);
}
Please have in mind that exactly the same headers and content sent via postman app to the resource, works fine but when I try to send it via Angular POST I get 403 forbidden without even triggering the filters. Also it works when I remove @Secure and Authorization header from Angular