how to keep session alive after page refresh - session

Please how do I keep the home session alive when a user refreshes the browser ?
Because after login, the home page session is alive. But when I refresh the browser, it takes me back to login page.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Maxwell
*/
#WebFilter(filterName = "sessionFilter", urlPatterns = {"/*"})
public class sessionFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req1 =(HttpServletRequest)request;
HttpServletResponse res1 =(HttpServletResponse)response;
String session = (String)req1.getSession().getAttribute("pnumber");
String currentPath = req1.getRequestURL().toString();
if(session != null)
{
if(currentPath.contains("login.xhtml"))
{
res1.sendRedirect(req1.getContextPath()+"/home.xhtml");
System.out.println("it is nt empty");
}
else
{
chain.doFilter(request, response);
}
//System.out.println("it is nt empty");
}
else
{
if(currentPath.contains("home"))
{
res1.sendRedirect(req1.getContextPath()+"/login.xhtml");
System.out.println("somefin is wrong");
}
else
{
chain.doFilter(request, response);
}
//System.out.println("somefin is wrong");
}
}
#Override
public void destroy() {
}
}
Please how do I keep the home session alive when a user refreshes the browser?
Because after login, the home page session is alive. But when I refresh the browser, it takes me back to login page.

is there any warning or error in the console when refreshing the page? Well, for session management in JSF, I'd do the following:
1) I'd use a ManagedBean #SessionScoped, where I'll keep the user info into a SessionMap once s/he has logged in:
public void login(){
//your code
if(validations){
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().getSessionMap().put("loggedUser", User);
//User is the entity which contains the current user info.
//You can use any data to keep in the SessionMap ;-)
}
}
2) When the user clicks on logout, you have invalidate the session:
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().invalidateSession();
3) Now if you want to validate the session when the user types the URL directly without logging in from the login page:
public void validateSession(){
FacesContext fc = FacesContext.getCurrentInstance();
User currentUser = (User) fc.getExternalContext().getSessionMap().get("loggedUser");
if(currentUser==null){
//shows a message 'Session has caducated'
fc.getExternalContext().redirect("./login.xhtml");
}
}
Then you just call the method before rendering the view:
<f:event type="preRenderView" listener="#{loginBean.validateSession()}" />
4) If you'd like to get the current user data from any managedBean, you have to get it from the SessionMap:
FacesContext fc = FacesContext.getCurrentInstance();
User user = (User) fc.getExternalContext().getSessionMap().get("loggedUser");
Hope this helps ;-)

Related

Spring security Session Timeout handling for Ajax calls redirect to login not working

There are a lot of questions like this one similar to my question but not working. I am following this blog to redirect ajax request to login page when session timeout but in my case it is not working. here is the code
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.security.web.util.ThrowableCauseExtractor;
import org.springframework.web.filter.GenericFilterBean;
public class AjaxTimeoutRedirectFilter extends GenericFilterBean{
private static final Logger logger = LoggerFactory.getLogger(AjaxTimeoutRedirectFilter.class);
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private int customSessionExpiredErrorCode = 901;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
try
{
chain.doFilter(request, response);
logger.debug("Chain processed normally");
}
catch (IOException ex)
{
throw ex;
}
catch (Exception ex)
{
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
RuntimeException ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
if (ase == null)
{
ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
}
if (ase != null)
{
if (ase instanceof AuthenticationException)
{
throw ase;
}
else if (ase instanceof AccessDeniedException)
{
if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication()))
{
HttpServletRequest httpReq = (HttpServletRequest) request;
logger.info("User session expired or not logged in yet");
String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxHeader))
{
logger.info("Ajax call detected, send {} error code", this.customSessionExpiredErrorCode);
((HttpServletResponse)response).sendRedirect("/home/login");
return;
}else
{
((HttpServletResponse)response).sendRedirect("/home/login");
logger.info("Redirect to login page");
return;
}
}
else
{
this.redirectStrategy.sendRedirect((HttpServletRequest) request, (HttpServletResponse) response,"/home/login");
return;
}
}
}
}
}
private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer
{
/**
* #see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
*/
protected void initExtractorMap()
{
super.initExtractorMap();
registerExtractor(ServletException.class, new ThrowableCauseExtractor()
{
public Throwable extractCause(Throwable throwable)
{
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class);
return ((ServletException) throwable).getRootCause();
}
});
}
}
public void setCustomSessionExpiredErrorCode(int customSessionExpiredErrorCode)
{
this.customSessionExpiredErrorCode = customSessionExpiredErrorCode;
}
}
I have added this <security:custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER"/> and the ajaxTimeoutRedirectFilter bean in the xml configuration file but not working. When i debug it goes to redirect code but the redirect is not redirecting to login.
As ajax call response status after redirect will be 200 instead of 302. There is no option left to identify redirection from status.
Instead of changing status code by implementing your own filter (order before ExceptionTranslationFilter), breaking filter chain by re-throwing exception.
Simple way is
1. Add this hidden div in login page.
<div style="display:none">LOGIN_PAGE_IDENTIFIER</div>
And in your each JSP page.(or, If you have any config.js which you include in every jsp page, add below code there)
<script type="text/javascript">
$(document).ajaxComplete(function (event, xhr, settings) {
if(xhr.responseText.indexOf("LOGIN_PAGE_IDENTIFIER") != -1)
window.location.reload();
});
</script>
PS:
About your concern regarding your AjaxTimeoutRedirectFilter
If you are receiving 901 status in ajax response then
$(document).ajaxComplete(function (event, xhr, settings) {
if(xhr.status == 901)
window.location.reload();
});
adding this to your every JSP page should solve your problem.

Spring - Redirect to a link upon successfully logging in, after a failed Ajax request

I have a website that requires some HTML to be rendered inside an element asynchronously upon an user action. If the user's session expires things get tricky, but it can be solved by creating a custom AuthenticationEntryPoint class like this SO question and this SO question suggest.
My problem comes once the user logs back in because the user gets redirected to the last URL that was requested, which happens to be the Ajax request, therefore my user gets redirected to a fragment of an HTML, instead of the last page it browsed.
I was able to solve this by removing a session attribute on the custom AuthenticationEntryPoint:
if (ajaxOrAsync) {
request.getSession().removeAttribute("SPRING_SECURITY_SAVED_REQUEST");
}
Here comes my question's problem.
While the previous code solves my issue, it has the side effect of redirecting the user to the home page instead of the last page it browsed (as there is no saved request). It wouldn't be much of a problem, but it makes the website inconsistent because if the last request was an asynchronous request, it gets redirected home but if it was a normal request it gets redirected to the last page browsed. =(
I managed to code this to handle that scenario:
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.PortResolver;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import static org.apache.commons.lang.StringUtils.isBlank;
public class CustomAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
... // Some not so relevant code
#Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
... // some code to determine if the request is an ajax request or an async one
if (ajaxOrAsync) {
useRefererAsSavedRequest(request);
response.sendError(SC_UNAUTHORIZED);
} else {
super.commence(request, response, authException);
}
}
private void useRefererAsSavedRequest(final HttpServletRequest request) {
request.getSession().removeAttribute(SAVED_REQUEST_SESSION_ATTRIBUTE);
final URL refererUrl = getRefererUrl(request);
if (refererUrl != null) {
final HttpServletRequestWrapper newRequest = new CustomHttpServletRequest(request, refererUrl);
final PortResolver portResolver = new PortResolverImpl();
final DefaultSavedRequest newSpringSecuritySavedRequest = new DefaultSavedRequest(newRequest, portResolver);
request.getSession().setAttribute(SAVED_REQUEST_SESSION_ATTRIBUTE, newSpringSecuritySavedRequest);
}
}
private URL getRefererUrl(final HttpServletRequest request) {
final String referer = request.getHeader("referer");
if (isBlank(referer)) {
return null;
}
try {
return new URL(referer);
} catch (final MalformedURLException exception) {
return null;
}
}
private class CustomHttpServletRequest extends HttpServletRequestWrapper {
private URL url;
public CustomHttpServletRequest(final HttpServletRequest request, final URL url) {
super(request);
this.url = url;
}
#Override
public String getRequestURI() {
return url.getPath();
}
#Override
public StringBuffer getRequestURL() {
return new StringBuffer(url.toString());
}
#Override
public String getServletPath() {
return url.getPath();
}
}
}
The previous code solves my issue, but it is a very hacky approach to solve my redirection problem (I cloned and overwrote the original request... +shudders+).
So my question is, Is there any other way to rewrite the link that Spring uses to redirect the user after a successful login (given the conditions I'm working with)?
I've looked at Spring's AuthenticationSuccessHandler, but I haven't found a way of communicating the referer url to it in case of a failed Ajax request.
I've found an acceptable solution to my problem thanks to an idea that came up when reading the docs and later on browsing this other SO answer. In short, I would have to create my own custom ExceptionTranslationFilter, and override the sendStartAuthentication to not to save the request cache.
If one takes a look at the ExceptionTranslationFilter code, it looks this (for Finchley SR1):
protected void sendStartAuthentication(HttpServletRequest request,
HttpServletResponse response, FilterChain chain,
AuthenticationException reason) throws ServletException, IOException {
SecurityContextHolder.getContext().setAuthentication(null);
requestCache.saveRequest(request, response); // <--- Look at me
logger.debug("Calling Authentication entry point.");
authenticationEntryPoint.commence(request, response, reason);
}
So, to not save data from Ajax requests I should implement an CustomExceptionTranslationFilter that acts like this:
#Override
protected void sendStartAuthentication(final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain chain,
final AuthenticationException authenticationException) throws ServletException, IOException {
... // some code to determine if the request is an ajax request or an async one
if (isAjaxOrAsyncRequest) {
SecurityContextHolder.getContext().setAuthentication(null);
authenticationEntryPoint.commence(request, response, authenticationException);
} else {
super.sendStartAuthentication(request, response, chain, authenticationException);
}
}
This makes the CustomAuthenticationEntryPoint logic much simpler:
#Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
... // some code to determine if the request is an ajax request or an async one, again
if (isAjaxOrAsyncRequest) {
response.sendError(SC_UNAUTHORIZED);
} else {
super.commence(request, response, authException);
}
}
And my CustomWebSecurityConfigurerAdapter should be configured like this:
#Override
protected void configure(final HttpSecurity http) throws Exception {
final CustomAuthenticationEntryPoint customAuthenticationEntryPoint =
new CustomAuthenticationEntryPoint("/login-path");
final CustomExceptionTranslationFilter customExceptionTranslationFilter =
new CustomExceptionTranslationFilter(customAuthenticationEntryPoint);
http.addFilterAfter(customExceptionTranslationFilter, ExceptionTranslationFilter.class)
....
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
....;
}

Flash Attribute in custom AuthenticationFailureHandler

On login failure I want to redirect the user to an error page and display a meaningful error message. Is it possible to add Flash Attributes that will be passed to the subsequent request?
The code presented below doesn't work. RequestContextUtils.getOutputFlashMap() returns null.
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler
{
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException
{
FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
if (outputFlashMap != null)
{
outputFlashMap.put("error", "Error message");
}
response.sendRedirect(request.getContextPath() + "/error");
}
}
I encountered this same problem with Spring 4.3.17 and finally found a solution by stepping through the spring-webmvc code and making educated guesses about how to integrate Flash Attributes outside the normal framework. SessionFlashMapManager is the key to getting this to work. I believe this method should work for Spring 3.1.1+.
package org.myorg.spring.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.FlashMapManager;
import org.springframework.web.servlet.support.SessionFlashMapManager;
#Component
public final class FlashAuthenticationFailureHandler implements AuthenticationFailureHandler
{
/**
* Flash attribute name to save on redirect.
*/
public static final String AUTHENTICATION_MESSAGE = "FLASH_AUTHENTICATION_MESSAGE";
public FlashAuthenticationFailureHandler()
{
return;
}
#Override
public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException, ServletException
{
if (exception != null)
{
final FlashMap flashMap = new FlashMap();
// Don't send the AuthenticationException object itself because it has no default constructor and cannot be re-instantiated.
flashMap.put(AUTHENTICATION_MESSAGE, exception.getMessage());
final FlashMapManager flashMapManager = new SessionFlashMapManager();
flashMapManager.saveOutputFlashMap(flashMap, request, response);
}
response.sendRedirect(request.getHeader("referer"));
return;
}
}
Then in the controller(s) that requires the flash attribute, simply add a ModelAttribute with the same name:
#RequestMapping(value = {"/someview"}, method = RequestMethod.GET)
public String getSomePage(final Authentication authentication, #ModelAttribute(FlashAuthenticationFailureHandler.AUTHENTICATION_MESSAGE) final String authenticationMessage, final Model model) throws Exception
{
if (authenticationMessage != null)
{
model.addAttribute("loginMessage", authenticationMessage);
}
return "myviewname";
}
Then the page attribute containing the message can be accessed in your JSP as follows:
<c:if test="${not empty loginMessage}">
<div class="alert alert-danger"><c:out value="${loginMessage}" /></div>
</c:if>
I'd guess it's null because you are calling the function from the filter chain, whereas the flash map is maintained by Spring's DispatcherServlet which the request hasn't passed through at this point.
Why not just use a parameter? i.e
response.sendRedirect(request.getContextPath()+"/error?error=" + "Error Message");

Pages restricted by login filter are still accessible by other users

I am using Filters in my login application. I want some pages only
accessed by admin. I have kept those pages in admin folder and
implemented filters in my project. But pages are still accessible
through URL by other users.
Where I am going wrong?
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginFilter implements Filter {
#Override
public void init(FilterConfig config) throws ServletException {
// If you have any <init-param> in web.xml, then you could get them
// here by config.getInitParameter("name") and assign it as field.
}
#Override
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);
if (session == null || session.getAttribute("user") == null) {
response.sendRedirect(request.getContextPath() + "/Login.xhtml"); // No logged-in user found, so redirect to login page.
} else {
chain.doFilter(req, res); // Logged-in user found, so just continue request.
}
}
#Override
public void destroy() {
// If you have assigned any expensive resources as field of
// this Filter class, then you could clean/close them here.
}
}
Theoretically there are 2 possible reasons for this:
The filter doesn't run at all
The filter doesn't protect the pages of the application.
I know it sounds trivially but could you specify whether the filter runs at all, and if yes, do you come to chain.doFilter(req,res) ?

How do I get the Session Object in Spring?

I am relatively new to Spring and Spring security.
I was attempting to write a program where I needed to authenticate a user at the server end using Spring security,
I came up with the following:
public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
#Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
throws AuthenticationException
{
System.out.println("Method invoked : additionalAuthenticationChecks isAuthenticated ? :"+usernamePasswordAuthenticationToken.isAuthenticated());
}
#Override
protected UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException
{
System.out.println("Method invoked : retrieveUser");
//so far so good, i can authenticate user here, and throw exception if not authenticated!!
//THIS IS WHERE I WANT TO ACCESS SESSION OBJECT
}
}
My usecase is that when a user is authenticated, I need to place an attribute like:
session.setAttribute("userObject", myUserObject);
myUserObject is an object of some class that I can access throughout my server code across multiple user requests.
Your friend here is org.springframework.web.context.request.RequestContextHolder
// example usage
public static HttpSession session() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attr.getRequest().getSession(true); // true == allow create
}
This will be populated by the standard spring mvc dispatch servlet, but if you are using a different web framework you have add org.springframework.web.filter.RequestContextFilter as a filter in your web.xml to manage the holder.
EDIT: just as a side issue what are you actually trying to do, I'm not sure you should need access to the HttpSession in the retieveUser method of a UserDetailsService. Spring security will put the UserDetails object in the session for you any how. It can be retrieved by accessing the SecurityContextHolder:
public static UserDetails currentUserDetails(){
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null) {
Object principal = authentication.getPrincipal();
return principal instanceof UserDetails ? (UserDetails) principal : null;
}
return null;
}
Since you're using Spring, stick with Spring, don't hack it yourself like the other post posits.
The Spring manual says:
You shouldn't interact directly with the HttpSession for security
purposes. There is simply no justification for doing so - always use
the SecurityContextHolder instead.
The suggested best practice for accessing the session is:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
The key here is that Spring and Spring Security do all sorts of great stuff for you like Session Fixation Prevention. These things assume that you're using the Spring framework as it was designed to be used. So, in your servlet, make it context aware and access the session like the above example.
If you just need to stash some data in the session scope, try creating some session scoped bean like this example and let autowire do its magic. :)
i made my own utils. it is handy. :)
package samples.utils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
/**
* SpringMVC通用工具
*
* #author 应卓(yingzhor#gmail.com)
*
*/
public final class WebContextHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);
private static WebContextHolder INSTANCE = new WebContextHolder();
public WebContextHolder get() {
return INSTANCE;
}
private WebContextHolder() {
super();
}
// --------------------------------------------------------------------------------------------------------------
public HttpServletRequest getRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attributes.getRequest();
}
public HttpSession getSession() {
return getSession(true);
}
public HttpSession getSession(boolean create) {
return getRequest().getSession(create);
}
public String getSessionId() {
return getSession().getId();
}
public ServletContext getServletContext() {
return getSession().getServletContext(); // servlet2.3
}
public Locale getLocale() {
return RequestContextUtils.getLocale(getRequest());
}
public Theme getTheme() {
return RequestContextUtils.getTheme(getRequest());
}
public ApplicationContext getApplicationContext() {
return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}
public ApplicationEventPublisher getApplicationEventPublisher() {
return (ApplicationEventPublisher) getApplicationContext();
}
public LocaleResolver getLocaleResolver() {
return RequestContextUtils.getLocaleResolver(getRequest());
}
public ThemeResolver getThemeResolver() {
return RequestContextUtils.getThemeResolver(getRequest());
}
public ResourceLoader getResourceLoader() {
return (ResourceLoader) getApplicationContext();
}
public ResourcePatternResolver getResourcePatternResolver() {
return (ResourcePatternResolver) getApplicationContext();
}
public MessageSource getMessageSource() {
return (MessageSource) getApplicationContext();
}
public ConversionService getConversionService() {
return getBeanFromApplicationContext(ConversionService.class);
}
public DataSource getDataSource() {
return getBeanFromApplicationContext(DataSource.class);
}
public Collection<String> getActiveProfiles() {
return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
}
public ClassLoader getBeanClassLoader() {
return ClassUtils.getDefaultClassLoader();
}
private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
try {
return getApplicationContext().getBean(requiredType);
} catch (NoUniqueBeanDefinitionException e) {
LOGGER.error(e.getMessage(), e);
throw e;
} catch (NoSuchBeanDefinitionException e) {
LOGGER.warn(e.getMessage());
return null;
}
}
}
Indeed you can access the information from the session even when the session is being destroyed on an HttpSessionLisener by doing:
public void sessionDestroyed(HttpSessionEvent hse) {
SecurityContextImpl sci = (SecurityContextImpl) hse.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
// be sure to check is not null since for users who just get into the home page but never get authenticated it will be
if (sci != null) {
UserDetails cud = (UserDetails) sci.getAuthentication().getPrincipal();
// do whatever you need here with the UserDetails
}
}
or you could also access the information anywhere you have the HttpSession object available like:
SecurityContextImpl sci = (SecurityContextImpl) session().getAttribute("SPRING_SECURITY_CONTEXT");
the last assuming you have something like:
HttpSession sesssion = ...; // can come from request.getSession(false);
I try with next code and work excellent
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by jaime on 14/01/15.
*/
#Controller
public class obteinUserSession {
#RequestMapping(value = "/loginds", method = RequestMethod.GET)
public String UserSession(ModelMap modelMap) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
modelMap.addAttribute("username", name);
return "hellos " + name;
}
In my scenario, I've injected the HttpSession into the CustomAuthenticationProvider class
like this
public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
#Autowired
private HttpSession httpSession;
#Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
throws AuthenticationException
{
System.out.println("Method invoked : additionalAuthenticationChecks isAuthenticated ? :"+usernamePasswordAuthenticationToken.isAuthenticated());
}
#Override
protected UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException
{
System.out.println("Method invoked : retrieveUser");
//so far so good, i can authenticate user here, and throw exception
if not authenticated!!
//THIS IS WHERE I WANT TO ACCESS SESSION OBJECT
httpSession.setAttribute("userObject", myUserObject);
}
}
If all that you need is details of User, for Spring Version 4.x you can use #AuthenticationPrincipal and #EnableWebSecurity tag provided by Spring as shown below.
Security Configuration Class:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
}
Controller method:
#RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(#AuthenticationPrincipal User user) {
...
}
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
attr.getSessionId();

Resources