HttpServletRequest getting new session - session

I have an application that does authentication via oauth.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
// Check if already logged in
if (getUser(httpReq) != null) {
chain.doFilter(request, response);
return;
}
// Try to parse auth response
if (procAuthResponse(httpReq)) {
chain.doFilter(request, response);
return;
}
// Go to auth server
sendAuthRequest(httpReq, httpResp);
}
This works fine.
In the method procAuthResponse I am paring the response from the server and to this.
HttpSession session = request.getSession();
session.setAttribute(USER_PRINCIPLE_ATR, userInfo);
It works also well, but there is a session scoped class with the method getCurrent user, that is used by servlets.
public UserInfo getCurrentUser() {
HttpSession session = getHttpSession();
if (session == null) {
LOG.warn("Method getCurrentUser: unable to find a session");
return null;
}
Object user = session.getAttribute(OAuthLoginFilter.USER_PRINCIPLE_ATR);
if (!(user instanceof UserInfo)) {
LOG.warn(String.format("Method getCurrentUser, wrong type for attribute %s", OAuthLoginFilter.USER_PRINCIPLE_ATR));
return null;
}
currentUser = (UserInfo) user;
return currentUser;
}
This method gets called multiple times and it turnes out that on the first call everything works as expected and after that the getHttpSession() returns a different session that does not contain any information that is set in the filter class. It is not a new session every time, the session without the needed information is always the same.
Code of getHttpSession()
private HttpSession getHttpSession() {
Object request = FacesContext.getCurrentInstance().getExternalContext().getRequest();
if (!(request instanceof HttpServletRequest)) {
LOG.warn("not a valid http request");
return null;
}
HttpServletRequest hreq = (HttpServletRequest) request;
return hreq.getSession(false);
}
Do you have any idea why this happens?
Thx for your help

There was still an old filter class, not configured in the web.xml, but annotated with #WebFilter("/*").
I deleted this file and now everything works as expected.

Related

Spring Security exclude URL in timeout

In Spring Security, how to exclude one particular URL from resetting the session timeout? Overall application session timeout(server.servlet.session.timeout) is 15 minutes. We have a ajax call from the web page that will get called every 1 minute. This call needs to be secured, but should not impact the session time.
We have tried adding a filter extending ConcurrentSessionFilter. Also, a filter extending SessionManagementFilter. Adding ignoring() skips authentication too. Nothing helped. Can this requirement be achieved in Spring Security? Any suggestions?
This is how i handled it. Just sharing, it may be of help to someone. Please share any better ways.
Spring Security filter is added as last in the chain.
http.addFilterAfter(new SessionInvalidationFilter(timeOutInMinutes), SwitchUserFilter.class);
It keeps track of a lastUpdatedTime, which gets updated for all calls except for those URLs that needs to be ignored. In case, the differential time is greater than the configured timeout, session gets invalidated.
public class SessionInvalidationFilter extends GenericFilterBean {
private static final String LASTUPDATEDDATETIME = "LASTUPDATEDDATETIME";
private static final List<String> ignoredURLs = Arrays.asList("/Notifications/number"); // this is the AJAX URL
private int timeOutInMinutes = 15;
public SessionInvalidationFilter(int timeOutInMinutes) {
this.timeOutInMinutes = timeOutInMinutes;
}
#Override
/**
* LASTUPDATEDDATETIME is updated for all calls except the ignoredURLs.
* Session invalidation happens only during the ignoredURLs calls.
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
try {
if (session != null && request.getRequestURI() != null) {
if (ignoredURLs.contains(request.getRequestURI())) {
Object lastUpdatedDateTimeObject = session.getAttribute(LASTUPDATEDDATETIME);
if (lastUpdatedDateTimeObject != null) {
LocalDateTime lastUpdatedDateTime = (LocalDateTime) lastUpdatedDateTimeObject;
long timeInMinutes = ChronoUnit.MINUTES.between(lastUpdatedDateTime, LocalDateTime.now());
if (timeInMinutes >= timeOutInMinutes) {
log.info("Timing out sessionID:{}", session.getId());
session.invalidate();
SecurityContextHolder.clearContext();
}
}
} else {
session.setAttribute(LASTUPDATEDDATETIME, LocalDateTime.now());
}
}
} catch (Exception e) {
log.error("Exception in SessionInvalidationFilter", e);
}
chain.doFilter(request, response);
}
}

Session Tracking Login in spring mvc

I'm new using spring mvc in general. I'm generating login page and my problem is that it always redirects me to the notLoggedIn prompt after I've tried to log in.
The controller:
#RequestMapping(value="/login", method= RequestMethod.POST) //login
public String logIn(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
HttpSession session= request.getSession();
request.getSession().setAttribute("isLoggedIn", "true");
String uname=request.getParameter("userid");
String pword=request.getParameter("password");
boolean exists=logInService.checkLogIn(uname, pword);
if(exists){
session.setAttribute("userid", uname);
return "Users"; //return to next success login jsp
} else {
return "Interface2"; //return to Invalid username and password jsp
}
}
The interceptor:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session= request.getSession();
if(session.getAttribute("userid")!=null && session.getAttribute("isLoggedIn")!=null ){
System.out.println("Logged In");
}
else{
response.sendRedirect(request.getContextPath()+"/modulename/notLoggedIn");
System.out.println("Not logged in");
return false;
}
return true;
}
Your interceptor blocks every http request and does some check but it should actually allow and not check for login http request. Following changes are just to get the use case work. Refer note at the bottom for suggestions.
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session= request.getSession();
if(session.getAttribute("userid")!=null && session.getAttribute("isLoggedIn")!=null ){
//user has already logged in . so therefore can access any resource
System.out.println("Logged In");
return true;
}
//if code reaches here means that user is not logged in
//allow login http request. modify checks accordingly. like you can put strict equals.
if (request.getRequestURI().endsWith("/login")){
//user is not logged in but is trying to login. so allow only login requests
return true;
}
else{
//user is not logged in and is trying to access a resource. so redirect him to login page
response.sendRedirect(request.getContextPath()+"/modulename/notLoggedIn");
System.out.println("Not logged in");
return false;
}
}
Note: You can reorder your login http request check to avoid login request for already logged in user.

JSF ajax request calls filter (should be ignored!)

I have some filters, which grab e.g. a parameter like "id" to check some right (used to load some contents). These filters should ignore all ajax-requests, because e.g. the rights does not have to be checked after every little request (only on page load)
The Problem is, that when I perform an ajax-request, it throws me a null-pointer, because I don't append the ID with ajax requests. I found out, that it still works, when I use and it fails, when I use (both perform ajax requests).
This is my filter:
public class ExtendedAccessFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
//ignore filter if it is an ajax-request (DOES NOT WORK if not p:commandButton!)
if(isAJAXRequest(req)){
chain.doFilter(request, response);
System.out.println("ABORT FILTER, AJAX");
return;
}
//Nullpointer thrown here (because no Id is submitted)
int requestedId = Integer.parseInt(request.getParameter("id"));
}
private boolean isAJAXRequest(HttpServletRequest request) {
boolean check = false;
String facesRequest = request.getHeader("Faces-Request");
if (facesRequest != null && facesRequest.equals("partial/ajax")) {
check = true;
}
return check;
}
}
Am I doing something wrong?
You are doing it right way. You can also do it using JSF API by checking if PartialViewContext exists and it is an Ajax Request
if(FacesContext.getCurrentInstance().getPartialViewContext() !=null &&
FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) {
}

Spring security custom session timeout

I am using spring security with my spring mvc webapp and I am trying to implement a custom session expiry. My requirement is when the session expired I need to retreive the user for which the session expired and then grab something from their security contexxt and write it to the redirect url.
The problem I am facing is that on session timeout the security context is not the user for which the session has timed out. Instead the security context comes out as anonymous user.
How can I get org.springframework.security.web.session.SessionManagementFilter to pass the user for which the session has timed out into onInvalidSessionDetected(request, response);
Here is the method in SessionManagementFilter where I need to somehow get the user for which the session timeout is happening and pass it to invalidSessionStrategy. Or alternatively can I just grab that inside invalidSessionStrategy.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
}
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
if (!securityContextRepository.containsContext(request)) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !authenticationTrustResolver.isAnonymous(authentication)) {
// The user has been authenticated during the current request, so call the session strategy
try {
sessionAuthenticationStrategy.onAuthentication(authentication, request, response);
} catch (SessionAuthenticationException e) {
// The session strategy can reject the authentication
logger.debug("SessionAuthenticationStrategy rejected the authentication object", e);
SecurityContextHolder.clearContext();
failureHandler.onAuthenticationFailure(request, response, e);
return;
}
// Eagerly save the security context to make it available for any possible re-entrant
// requests which may occur before the current request completes. SEC-1396.
securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
} else {
// No security context or authentication present. Check for a session timeout
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
logger.debug("Requested session ID" + request.getRequestedSessionId() + " is invalid.");
if (invalidSessionStrategy != null) {
invalidSessionStrategy.onInvalidSessionDetected(request, response);
return;
}
}
}
}
chain.doFilter(request, response);
}
When I do Authentication authentication = securityContext.getAuthentication(); inside onInvalidSessionDetected I get an anonymous user which is not what I want.
thanks

Spring Security: How to get the initial target url

I am using the spring security to restricted urls. I am trying to provide signup and login page, on the same page.
On login spring security transfers to the restricted page. However i am trying to pass the target url to the signup process, so that after signup we can redirect to the restricted page.
How to get the actual URL that user was redirected from.
Any Ideas?
This is how i got the URL from the Spring Security.
SavedRequest savedRequest = (SavedRequest)session.getAttribute(
AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);
String requestUrl = savedRequest.getFullRequestUrl();
They moved things around a bit in spring security 3.0, so the above code snippet doesn't work anymore. This does the trick, though:
protected String getRedirectUrl(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if(session != null) {
SavedRequest savedRequest = (SavedRequest) session.getAttribute(WebAttributes.SAVED_REQUEST);
if(savedRequest != null) {
return savedRequest.getRedirectUrl();
}
}
/* return a sane default in case data isn't there */
return request.getContextPath() + "/";
}
with spring security 4.1.4:
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
if (savedRequest != null) {
response.sendRedirect(savedRequest.getRedirectUrl());
}
else{
response.sendRedirect("some/path");
}
}
DefaultSavedRequest savedRequest = (DefaultSavedRequest)session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
String requestURL = savedRequest.getRequestURL(); // URL <br>
String requestURI = savedRequest.getRequestURI(); // URI

Resources