How to design a session-less JSF 2.0 web application? - session

I am working on a JSF 2.0 website. The website has two kind of users(public and registered). Now I want to know that how can I create session for both kind of users? For registered users, when my user is login then there should be session for it, and when session expires then I redirect it to page that your session has expired. For public users there should be no session at all. Means there is no session time out for my public users and they never have messages that your session has expired. How can I implement this behavior in JSF 2.0.
Can I use filter for it or there is better approach for it? I also read that JSF automatically creates session using managed beans. Can I use these sessions for my task?
Edit:
I tell you what i did so you people better guide me in this scenerio
What i did i put a filter in my web app like this
<filter>
<filter-name>SessionTimeoutFilter</filter-name>
<filter-class>util.SessionTimeoutFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionTimeoutFilter</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
Here is my Filter code
public class SessionTimeoutFilter implements Filter {
// This should be your default Home or Login page
// "login.seam" if you use Jboss Seam otherwise "login.jsf"
// "login.xhtml" or whatever
private String timeoutPage = "faces/SessionExpire.xhtml";
private String welcomePage = "faces/index.xhtml";
public static Boolean expirePage = false;
private FilterConfig fc;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.fc = filterConfig;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession();
/**
* The session objects have a built-in data structure (a hash table) in which you can store
* any number of keys and associated values. You use session.getAttribute("key") to look up
* a previously stored value. The return type is Object, so you must do a typecast to
* whatever more specific type of data was associated with that attribute name in the session.
* The return value is null if there is no such attribute, so you need to check for null
* before calling methods on objects associated with sessions.
*
* Note:
* JSF session scoped managed beans are under the covers stored as a HttpSession
* attribute with the managed bean name as key.
*/
Login login = (Login)session.getAttribute("login");
if (login == null) { // No such object already in session
filterChain.doFilter(request, response);
} else {
/**
* If you use a RequestDispatcher, the target servlet/JSP receives the same
* request/response objects as the original servlet/JSP. Therefore, you can pass
* data between them using request.setAttribute(). With a sendRedirect(), it is a
* new request from the client, and the only way to pass data is through the session or
* with web parameters (url?name=value).
*/
filterChain.doFilter(request, response);
}
System.out.println();
} //end of doFilter()
#Override
public void destroy() {
} //end of destroy()
Now what happen that if you first time enter url of my site then this filter invoke. It gets
Login login = (Login)session.getAttribute("login");
null. So it simply move to my index.xhtml page. Now my index.html page constructor invokes. Here is my code
#ManagedBean
//////#RequestScoped
#SessionScoped
public class Login implements Serializable {
//Constructor
public Login() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
session.setAttribute("logedin", 0); //public user
session.setMaxInactiveInterval(-1); // no session time out
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
/**
* Here you also get "login" attr. Because when managed bean create the
* session, it sets you managedBean name in the session attribute.
*/
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
}
}//end of constructor
} //end of class Login
when first time user come to my site then it is not login so i set logedin session attribute 0. Now suppose user enter credentials and press log in button. First my filter is invoke but this time it will get login attribute and comes to my doFilter() else check and then come to My validUser() method. Here is my code
public String validUser() throws Exception {
ArrayList2d<Object> mainarray = new ArrayList2d<Object>();
mainarray.addRow();
mainarray.add(userName);
mainarray.add(password);
busBeans.usermanagement.users um = new busBeans.usermanagement.users();
ArrayList retrieveList = um.getValidUser(mainarray); //database check of user existence
if (Integer.parseInt(retrieveList.get(0).toString()) == 0) {
ArrayList str = (ArrayList) retrieveList.get(1);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
}
logedin=true;
session.setAttribute("logedin", 1);
session.setAttribute("firstLastName", str.get(7).toString());
session.setAttribute("getusercredentials", str);
session.setAttribute("sessionUserId", str.get(0).toString());
session.setAttribute("sessionRoleId",str.get(1).toString());
firstLastName = session.getAttribute("firstLastName").toString();
session.setMaxInactiveInterval(60); //1 min
ConnectionUtil.setRgihts(Integer.parseInt(str.get(0).toString()) , Integer.parseInt(str.get(1).toString()) ,Integer.parseInt(str.get(5).toString()));
checkRgihts();
}
} //end of validUser()
Now i want to ask one thing. I set sessionTimeout using setMaxInterval. Is it ok or it is better to do in web.xml? Now whne timeOut expires then filter doesn't invoke. But suppose that I also attach HttpSessionListener. Then on session time Out its destroy method invoke. I can invalidate session here. Like this.
public class MySessionListener implements HttpSessionListener {
// Constructor
public MySessionListener() {
} //end of constructor
#Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Current Session created : " + event.getSession().getCreationTime());
System.out.println();
} //end of sessionCreated()
#Override
public void sessionDestroyed(HttpSessionEvent event) {
// get the destroying session...
HttpSession session = event.getSession();
if (session != null) {
session.invalidate();
}
System.out.println();
} //end of sessionDestroyed()
} //end of class MySessionListener
But on session expiration i also want to redirect user to redirecr Page if this is a registered user. IF this is a public user i don't want to redirect it although session has expired. I can check in the destroy method by getting attribute logedin that it is a public user or registered user. But then how can i redirect for registered user or do nothing for public user.
If somehow my filter invoke on session time out and some how i check that if this is a registered user by getting logedin attribute 1 and session time out has expired, because for public user i set timeout -1, then redirect the user, using RequestDispatcher otherwoise do filterChain.doFilter(request, response);.
So this is the scenerio that i implemented. I don't know whether my approaches are right or not ? I don't know what security issues i will face by this approach. So that's it.. Now you people guide me what should i do.....
Thanks

I understand what your goal is, but I don't think that not having a Session for unauthenticated users is particularly the best approach.
Consider an unauthenticated user navigating through a Primefaces wizard as he provides information to sign up for an account, (Eg. Pick Username, Provide Password, Choose Security Questions, etc...)
You are not going to want to persist this user information until it all has been collected and validated, because perhaps the user has a change of heart and decides not to sign up? Now you have an incomplete user record in your database that needs to be cleaned.
The answer is that you need to store this information in a ViewScoped bean or in session until the unauthenticated user confirms the account creation, where it can finally be persisted.
What I feel the best approach would be is for you to give a User a unique Role with one role being Unauthenticated. Using components like Spring Security 3 or even Seam you should be able to control page Authorization through the Role of the User in Session.
For instance, you can prevent unauthenticated users from entering pages in ../app/* or normal users from accessing pages in ../admin/*

I used some thing like this. First there is a filter. Here is my filter
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//Send request to server after each 1min
// httpServletResponse.setIntHeader("Refresh", 60);
//getSession(false), which returns null if no session already exists for the current client
HttpSession session = httpServletRequest.getSession(false);
if (session == null) {
//session timeout check.
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
/**
* getSession() (or, equivalently, getSession(true)) creates a new session if no
* session already exists.
*/
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0"); // public user
//httpServletResponse.sendRedirect("http://www.google.com");
httpServletResponse.sendRedirect(timeoutPage);
} else {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
} else {
String isRegisteredUser = session.getAttribute("logedin").toString();
if (isRegisteredUser.equalsIgnoreCase(("1"))) {
Login login = (Login)session.getAttribute("login");
Enumeration e = session.getAttributeNames();
System.out.println("");
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else if (isRegisteredUser.equalsIgnoreCase(("0"))) {
Enumeration e = session.getAttributeNames();
filterChain.doFilter(httpServletRequest, httpServletResponse);
} //end of else if (isRegisteredUser.equalsIgnoreCase(("0")))
}
} //end of doFilter()
Now when user enter url of my site then this filter invoke. First time it get session null then it checks for session timeout. no session time out so it creates a session. Set logedin attribute to zero, means this is public user and pass the request. Here is my method
//constructor
public Login() {
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletRequest httpServletRequest = (HttpServletRequest)externalContext.getRequest();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
session.setMaxInactiveInterval(-1);
System.out.println();
} else {
session.setAttribute("logedin", "0");
//No session timeout for public users
session.setMaxInactiveInterval(-1);
Enumeration e = session.getAttributeNames();
}
} catch (Exception e) {
System.out.println("Exception in session " + e.getMessage());
}
} //end of constructor
First time it gets session, just override the values so there is no harm to set the same attribute. But here i just want to ask one thing that is it ok to set no session time out for public users ? will it damage my application at some point, like my server goes out of memory and etc ? If yes, then how can i overcome this ?
Now suppose that my user is log in. Then my filter invoke, this time it will get a session so it comes to my isRegisterdUser check and check the value. He get 0 , just pass the request and then my valid user method call.
public String validUser() throws Exception {
String returnString = null;
ArrayList2d<Object> mainarray = new ArrayList2d<Object>();
mainarray.addRow();
mainarray.add(userName);
mainarray.add(password);
busBeans.usermanagement.users um = new busBeans.usermanagement.users();
ArrayList retrieveList = um.getValidUser(mainarray);
if (Integer.parseInt(retrieveList.get(0).toString()) == 0) {
ArrayList str = (ArrayList) retrieveList.get(1);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
Enumeration e = session.getAttributeNames();
}
System.out.println();
logedin=true;
//Set session attributes for login users
session.setAttribute("logedin", 1);
session.setAttribute("firstLastName", str.get(7).toString());
session.setAttribute("getusercredentials", str);
session.setAttribute("sessionUserId", str.get(0).toString());
session.setAttribute("sessionRoleId",str.get(1).toString());
session.setAttribute("registeredUser", "true");
/**
* set session timeout for login user
* 1 min = 60 sec
* 5 min = 60 * 5 sec = 300 sec
*/
session.setMaxInactiveInterval(300); //5min
firstLastName = session.getAttribute("firstLastName").toString();
}
return returnString=null;
} //end of validUser()
I override the value of logedin attribute to 1 so now the user become valid user. Now if valid user make request then my filter invoke, it will get a session so it comes to my isRegisterdUser check, this time it get value 1 so just pass the request.Now when session time out and user make any request, then my filter invoke and this time it comes inside the check
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
//httpServletResponse.sendRedirect("http://www.google.com");
httpServletResponse.sendRedirect(timeoutPage);
} else {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
and redirect the user by making it public. So here how this i do it. I got also a idea that i refresh the page after some time, i have sessionCreationTime, sessionLastAccessTime and sessionMaxTime. so i can do a work like this
String isRegisteredUser = session.getAttribute("logedin").toString();
if (isRegisteredUser.equalsIgnoreCase(("1"))) {
Login login = (Login)session.getAttribute("login");
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
long sessionCreationTime = session.getCreationTime();
int sessionCreationTimeInSec = (int)(sessionCreationTime / 1000) % 60;
int sessionCreationTimeInMinutes = (int)((sessionCreationTime / (1000*60)) % 60);
long sessionLastAccessTime = session.getLastAccessedTime();
int sessionLastAccessTimeInSec = (int)(sessionLastAccessTime / 1000) % 60 ;
int sessionLastAccessTimeInMinutes = (int)((sessionLastAccessTime / (1000*60)) % 60 );
int sessionMaxTime = session.getMaxInactiveInterval();
int sessionMaxTimeInMinute = sessionMaxTime / 60 ;
if ((sessionCreationTimeInMinutes - sessionLastAccessTimeInMinutes) - 1 > sessionMaxTimeInMinute) {
System.out.println("Session is expiring in one minute");
}
System.out.println("");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
The idea here is that if some how you check that how much time left for session timeout then you can invalidate the session just before your session time out time. Because once your session expire you get session null and you have no attributes to check. But before one minute you have session and all session attributes so you can do whatever you want. I don't know how solid idea is this, it's just an approach that came to my mind.
Also suppose user is login and then suddenly closed the browser. Closing browser close the session. Now when you open your browser then you get a message that your session has expire. I want to ask when you open a browser can i use this check
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
if (session.isNew()) {
/**
* getSession() (or, equivalently, getSession(true)) creates a new session if no
* session already exists.
*/
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0"); // public user
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else {
httpServletResponse.sendRedirect("http://www.google.com");
}
}
I used isNew() check because i want to do that if user is entering your site first time, like open his browser, then he didn't see the redirection message although his session has been expired because of closing browser.
Thanks

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);
}
}

Spring Session Redis and Spring Security how to update user session?

I am building a spring REST web application using spring boot, spring secuirity, and spring session (redis). I am building a cloud application following the gateway pattern using spring cloud and zuul proxy. Within this pattern I am using spring session to manage the HttpSesssion in redis and using that to authorize requests on my resource servers. When an operation is executed that alters the session's authorities, I would like to update that object so that the user does not have to log out to have the updates reflected. Does anyone have a solution for this?
To update the authorities you need to modify the authentication object in two places. One in the Security Context and the other in the Request Context. Your principal object will be org.springframework.security.core.userdetails.User or extend that class (if you have overridden UserDetailsService). This works for modifying the current user.
Authentication newAuth = new UsernamePasswordAuthenticationToken({YourPrincipalObject},null,List<? extends GrantedAuthority>)
SecurityContextHolder.getContext().setAuthentication(newAuth);
RequestContextHolder.currentRequestAttributes().setAttribute("SPRING_SECURITY_CONTEXT", newAuth, RequestAttributes.SCOPE_GLOBAL_SESSION);
To update the session using spring session for any logged in user requires a custom filter. The filter stores a set of sessions that have been modified by some process. A messaging system updates that value when new sessions need to be modified. When a request has a matching session key, the filter looks up the user in the database to fetch the updates. Then it updates the "SPRING_SECURITY_CONTEXT" property on the session and updates the Authentication in the SecurityContextHolder. The user does not need to log out. When specifying the order of your filter it is important that it comes after SpringSessionRepositoryFilter. That object has an #Order of -2147483598 so I just altered my filter by one to make sure it is the next one that is executed.
The workflow looks like:
Modify User A Authority
Send Message To Filter
Add User A Session Keys to Set (In the filter)
Next time User A passed through the filter, update their session
#Component
#Order(UpdateAuthFilter.ORDER_AFTER_SPRING_SESSION)
public class UpdateAuthFilter extends OncePerRequestFilter
{
public static final int ORDER_AFTER_SPRING_SESSION = -2147483597;
private Logger log = LoggerFactory.getLogger(this.getClass());
private Set<String> permissionsToUpdate = new HashSet<>();
#Autowired
private UserJPARepository userJPARepository;
private void modifySessionSet(String sessionKey, boolean add)
{
if (add) {
permissionsToUpdate.add(sessionKey);
} else {
permissionsToUpdate.remove(sessionKey);
}
}
public void addUserSessionsToSet(UpdateUserSessionMessage updateUserSessionMessage)
{
log.info("UPDATE_USER_SESSION - {} - received", updateUserSessionMessage.getUuid().toString());
updateUserSessionMessage.getSessionKeys().forEach(sessionKey -> modifySessionSet(sessionKey, true));
//clear keys for sessions not in redis
log.info("UPDATE_USER_SESSION - {} - success", updateUserSessionMessage.getUuid().toString());
}
#Override
public void destroy()
{
}
#Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException
{
HttpSession session = httpServletRequest.getSession();
if (session != null)
{
String sessionId = session.getId();
if (permissionsToUpdate.contains(sessionId))
{
try
{
SecurityContextImpl securityContextImpl = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
if (securityContextImpl != null)
{
Authentication auth = securityContextImpl.getAuthentication();
Optional<User> user = auth != null
? userJPARepository.findByUsername(auth.getName())
: Optional.empty();
if (user.isPresent())
{
user.get().getAccessControls().forEach(ac -> ac.setUsers(null));
MyCustomUser myCustomUser = new MyCustomUser (user.get().getUsername(),
user.get().getPassword(),
user.get().getAccessControls(),
user.get().getOrganization().getId());
final Authentication newAuth = new UsernamePasswordAuthenticationToken(myCustomUser ,
null,
user.get().getAccessControls());
SecurityContextHolder.getContext().setAuthentication(newAuth);
session.setAttribute("SPRING_SECURITY_CONTEXT", newAuth);
}
else
{
//invalidate the session if the user could not be found
session.invalidate();
}
}
else
{
//invalidate the session if the user could not be found
session.invalidate();
}
}
finally
{
modifySessionSet(sessionId, false);
}
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}

Logout leaves behind JSESSIONID on the browser. How to clear it?

I am using the following code for logging out a user off my system.
/**
* This function helps to set the session attribute for the present user to null and then
* removes the attribute itself and this helps in clearing the session
* #param request
* #param response
*/
#RequestMapping(value = AuthConstants.EXIT, method = RequestMethod.POST)
public void exitPrime(HttpServletRequest request, HttpServletResponse response) {
/*Getting session and then invalidating it*/
HttpSession session = request.getSession(false);
if(request.isRequestedSessionIdValid() && session != null)
{
session.invalidate();
}
}
This leads to a successful logout but the JSESSION ID given by the while logging in still remains in the browser due to which for any new user the same JSESSION ID is used again while Logging In. I want the JSESSIONID cookie to be valid only for the current session and once the user logs out, it should be destroyed or invalid for the login done for the next time. My Login Code is as follows :-
/**
* This method allows one to log into the system and generates a token for a valid employee.
* #param authRequest
* #param request
* #param response
* #return
*/
#RequestMapping(value = AuthConstants.ENTRY, method = RequestMethod.POST, consumes = ApplicationConstants.APPLICATION_JSON)
public #ResponseBody
AuthResponse primeEntry(#RequestBody AuthRequest authRequest,HttpServletRequest request, HttpServletResponse response) {
AuthResponse authResponse = new AuthResponse();
if(authRequest != null && authRequest.getEmployeeAuth().getEmployeeNumber() != null
&& !authRequest.getEmployeeAuth().getEmployeeNumber().isEmpty()){
/*To check whether the user is valid*/
String employeeNumber = authRequest.getEmployeeAuth().getEmployeeNumber();
UserBean userBean = new UserBean();
userBean = userService.getUser(employeeNumber);
if(userBean != null)
{
HttpSession session = request.getSession(true);
session.setAttribute("user", userBean);
setAuthResponseSuccess(authResponse);
}else{
/*If user does not exist the too throw error 500*/
setAuthResponseFailure(authResponse);
}
}else{
/*If input JSON is not valid then throw error 500*/
setAuthResponseFailure(authResponse);
}
return authResponse;
}
I am using Spring 3.2 and want to do Login and Logout Manually. Please Help.
Full Class Code
#Controller
#RequestMapping(value = "/auth")
public class AuthController {
#Autowired
HttpServletRequest request;
#Autowired
HttpSession session;
#Autowired
IUserService userService;
/**
* This method allows one to log into the system and generates a token for a valid employee.
* #param authRequest
* #param request
* #param response
* #return
*/
#RequestMapping(value = AuthConstants.ENTRY, method = RequestMethod.POST, consumes = ApplicationConstants.APPLICATION_JSON)
public #ResponseBody
AuthResponse primeEntry(#RequestBody AuthRequest authRequest,HttpServletRequest request, HttpServletResponse response) {
AuthResponse authResponse = new AuthResponse();
if(authRequest != null && authRequest.getEmployeeAuth().getEmployeeNumber() != null
&& !authRequest.getEmployeeAuth().getEmployeeNumber().isEmpty()){
/*To check whether the user is valid*/
String employeeNumber = authRequest.getEmployeeAuth().getEmployeeNumber();
UserBean userBean = new UserBean();
userBean = userService.getUser(employeeNumber);
if(userBean != null)
{
HttpSession session = request.getSession(true);
session.setAttribute("user", userBean);
setAuthResponseSuccess(authResponse);
}else{
/*If user does not exist the too throw error 500*/
setAuthResponseFailure(authResponse);
}
}else{
/*If input JSON is not valid then throw error 500*/
setAuthResponseFailure(authResponse);
}
return authResponse;
}
/**
* This function helps to set the session attribute for the present user to null and then
* removes the attribute itself and this helps in clearing the session
* #param request
* #param response
*/
#RequestMapping(value = AuthConstants.EXIT, method = RequestMethod.POST)
public void exitPrime(HttpServletRequest request, HttpServletResponse response) {
/*Getting session and then invalidating it*/
HttpSession session = request.getSession(false);
if(request.isRequestedSessionIdValid() && session != null)
{
session.invalidate();
}
}
private AuthResponse setAuthResponseFailure(AuthResponse authResponse) {
authResponse.setResponseCode(ApplicationConstants.INTERNAL_ERROR_CODE);
authResponse.setStatus(StatusType.FAILURE);
authResponse.setResponseMsg(ApplicationConstants.INTERNAL_ERROR_MESSAGE);
return authResponse;
}
private AuthResponse setAuthResponseSuccess(AuthResponse authResponse){
authResponse.setResponseCode(ApplicationConstants.OK);
authResponse.setStatus(StatusType.SUCCESS);
authResponse.setResponseMsg(ApplicationConstants.LOGIN_SUCCESS);
return authResponse;
}
}
There's nothing wrong with JSESSIONID leftover on your browser as long as it's already invalid. JSESSIONID is just a bunch of random characters that don't contain your actual data.
However I suspect your problem is you used #SessionAttributes annotation at class level, and you attempted session.invalidate(). With this scenario after the previous session is invalidated, Spring automatically creates a new session (and JSESSIONID) for you because it has to persist specified model attributes into session.
IMO a better approach is to create a new controller that does not have #SessionAttributes and invalidate your session from there.
After experimenting a bit I reached to a conclusion that if you want the browser cookie value to persist then just dont do anything and the above code would work fine for you. On the other hand if you want the output of the cookie something like
Set-Cookie: JSESSIONID=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/
Then you can take this code snippet and try it out.
private void handleLogOutResponseCookie(HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setPath("/");
response.addCookie(cookie);
}
This would solve the problem and destroy the cookie while you logout.
Not sure if it still actual, but one can extend LogoutFilter like this to specify exact steps to be made on logout, including custom cookies invalidation.
<beans:bean id="sessionInvalidationFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<beans:property name="filterProcessesUrl" value="/logout"/>
<beans:constructor-arg>
<beans:array>
<beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
<beans:bean class="org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler">
<beans:constructor-arg value="JSESSIONID"/>
</beans:bean>
</beans:array>
</beans:constructor-arg>
</beans:bean>
One way I could think of is to delete the JSESSIONID cookie on logout action. The way to delete the cookie is to set its age to zero as follows.
Cookie cookie = new Cookie();
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath("/");
Here I have added the path as root. Please check JSESSIONID cookie in your browser for the correct path.
Once you have this, add this to the response
response.addCookie(cookie);
You can put this code in your exitPrime() method.
Tomcat appends a slash at the end of the context path. Now, when you set the delete-cookie attribute, Spring tries to find the cookie for the path without a slash at the end. Because it doesn't find it, the cookie will not be removed, resulting in the display of session expiration page instead of login page.
Following workaround will do the trick.
public void logout(HttpServletRequest request, HttpServletResponse response,
Authentication auth) {
Cookie cookieWithSlash = new Cookie("JSESSIONID", null);
//Tomcat adds extra slash at the end of context path (e.g. "/foo/")
cookieWithSlash.setPath(request.getContextPath() + "/");
cookieWithSlash.setMaxAge(0);
Cookie cookieWithoutSlash = new Cookie("JSESSIONID", null);
//JBoss doesn't add extra slash at the end of context path (e.g. "/foo")
cookieWithoutSlash.setPath(request.getContextPath());
cookieWithoutSlash.setMaxAge(0);
//Remove cookies on logout so that invalidSessionURL (session timeout) is not displayed on proper logout event
response.addCookie(cookieWithSlash); //For Tomcat
response.addCookie(cookieWithoutSlash); //For JBoss
}
The approach listed previously didn't work for me, but with some modification I got it to work, I've only done limited testing though so YMMV.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session != null) {
String sessionId = session.getId();
session.invalidate();
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if (sessionId.equalsIgnoreCase(cookie.getValue())) {
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setDomain(req.getServerName());
cookie.setPath(req.getServletContext().getContextPath() + "/");
cookie.setSecure(req.isSecure());
res.addCookie(cookie);
break;
}
}
}
}

Configure two cxf jaxrs clients to use the same session (cookies)

I want to connect to a REST server with a jaxrs client using apache cxf. The server has an url to authenticate and some other urls to do the actual stuff. After the login the server creates a session and keeps the connection open for 30 min. My problem is that the client doesn't store the cookies and I always get a new (not authenticated) session on the server.
I configured the clients in my spring application context.
<jaxrs:client id="loginResource"
serviceClass="com.mycompany.rest.resources.LoginResource"
address="${fsi.application.url}">
</jaxrs:client>
<jaxrs:client id="actionResource"
serviceClass="com.mycompany.rest.resources.ActionResource"
address="${fsi.application.url}">
</jaxrs:client>
How can I configure both clients to use the same session or share the session-cookie between the clients?
I have been struggling with the same problem, and I just finally arrived at a solution.
1) Make the client retain cookies.
WebClient.getConfig(proxy).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
Perhaps there's a way to accomplish the above via configuration vs. programmatically.
2) Copy the cookies from one client to the other.
public static void copyCookies(Object sourceProxy, Object targetProxy) {
HTTPConduit sourceConduit = WebClient.getConfig(sourceProxy).getHttpConduit();
HTTPConduit targetConduit = WebClient.getConfig(targetProxy).getHttpConduit();
targetConduit.getCookies().putAll(sourceConduit.getCookies());
}
After using proxy A to authenticate, I call the above method to share its cookies with proxy B, which does the actual work.
I use the following request/response filter to pass the session-id in each request:
ClientResponseFilter >> used to extract the session-id from session-cookie
ClientRequestFilter >> pass the session-id as cookie header in each request
private class SessionIdRequestFilter implements ClientRequestFilter, ClientResponseFilter {
/** cookie header key */
private static final String COOKIE_KEY = "Cookie"; //$NON-NLS-1$
/** name of the session cookie */
private String cookieName = "JSESSIONID";
/** holds the session id from the cookie */
private String sessionId;
#Override
public void filter(ClientRequestContext request) throws IOException {
// append session cookie to request header
if (!request.getHeaders().containsKey(COOKIE_KEY) && sessionId != null) {
request.getHeaders().add(COOKIE_KEY, getCookieName() + "=" + sessionId); //$NON-NLS-1$
}
}
#Override
public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException {
// find sessionId only if not already set
if (sessionId == null) {
Map<String, NewCookie> cookies = response.getCookies();
if (cookies != null && !cookies.isEmpty()) {
NewCookie cookie = cookies.get(getCookieName());
if (cookie != null) {
sessionId = cookie.getValue();
}
}
}
}
private String getCookieName() {
return cookieName;
}
}
To register the filter use:
RestClientBuilder.newBuilder().baseUri(apiUri).register(new SessionIdRequestFilter());

Invalidating session with CDI+JSF not working

I'm trying to implement a logout in my application, so I made this:
public String logout(){
try{
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext ex = facesContext .getExternalContext();
ex.invalidateSession();
return "success";
}catch(Exception e){
return "error";
}
}
But when I check if the user is logged, it says yes:
public class AuthenticateListener implements PhaseListener {
#Override
public void afterPhase(PhaseEvent event) {
AuthorizedUser authorized = (AuthorizedUser) Util.getHandler("authorized");
if (authorized.getUser() == null) {
System.out.println("Not Logged");
} else {
System.out.println("Logged");
}
}
#Override
public void beforePhase(PhaseEvent event) {
// TODO Auto-generated method stub
}
#Override
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}
Am I missing something? Shouldn't I get a new instance of AuthorizedUser (sessionScoped) after invalidating my session?
EDIT: Adding the getHandler, if someone needs it ;)
public static Object getHandler(String handlerName) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ELResolver resolver = facesContext.getApplication().getELResolver();
Object uh = resolver.getValue(elContext, null, handlerName);
return uh;
}
The session is still available in the current request-response. It's not available anymore in the next request. You need to send a redirect after the invalidate so that the browser will be instructed to send a new request on the given URL.
return "success?faces-redirect=true";
Or if you're still using old fashioned navigation cases (the return values namely suggests that; it's strange to have a view with filename "success"), then add <redirect/> to the navigation case instead.
If that still doesn't work, then the bug is in how you're storing the user in session. For example, it's instead actually been stored in the application scope which may happen when you mix CDI #Named with JSF #SessionScoped, or when you assigned the logged-in user as a static variable instead of an instance variable.
See also:
How to invalidate session in JSF 2.0?
Performing user authentication in Java EE / JSF using j_security_check
Use this piece of code inside logout method:
HttpSession oldsession = (HttpSession) FacesContext
.getCurrentInstance().getExternalContext().getSession(false);
oldsession.invalidate();
This will work. Let me know please if it was helpful for you.

Resources