Reputation: 53
I make HTTP calls from angular 7 client to Jersey REST service using Tomcat. The problem is that the session is lost after login.
I tried using different headers, but got no solution. I don't use a proxy. I use a CORS filter and a login+session filter that shows me that the session is lost after sucessful login. The session filter is only used afer login, in subsequent HTTP calls. I tested the service using POSTMAN and session is not lost in this case.
Angular call to HTTP login service:
public login(user: User): Observable<number> {
const url = 'http://localhost:8080/CouponsWebApp/user/login';
return this.httpService.post<number>(url, user, {withCredentials: true})
.pipe(catchError(this.messageService.handleError<number>('login'))
);
}
CORSFilter in server:
res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
Login and session filter in server:
HttpSession session = ((HttpServletRequest) request).getSession(false);
System.out.println("session=" + session);
if (session == null) { // session expired
try {
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/user/login");
return;
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
CouponClientFacade couponClientFacade = (CouponClientFacade) session.getAttribute("CouponClientFacade");
System.out.println("couponClientFacade=" + couponClientFacade);
if (couponClientFacade == null) { // not logged in
try {
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/user/login");
return;
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
I expected to get the session in session filter, but it prints session=null.
Upvotes: 0
Views: 504
Reputation: 53
The solution that worked for me was to add some parameters in Chrome, useful for dev environment only:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:\temp-chrome"
Upvotes: 1
Reputation: 12206
you should add {withCredentials: true}
to all of the request, not just login. it forces http requests to send cookies with it, and, as a result, session could be retrieved
Upvotes: 0