Example usage for javax.servlet.http HttpSession getId

List of usage examples for javax.servlet.http HttpSession getId

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getId.

Prototype

public String getId();

Source Link

Document

Returns a string containing the unique identifier assigned to this session.

Usage

From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.auth.OpenStackAuthenticationFilterTest.java

@Test
public void doFilterTestAnyPath() throws IOException, ServletException {
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    HttpSession httpSession = mock(HttpSession.class);
    Authentication authResult = mock(Authentication.class);
    PaasManagerUser paasUser = mock(PaasManagerUser.class);

    when(servletRequest.getHeader(anyString())).thenReturn("3df25213cac246f8bccad5c70cb3582e")
            .thenReturn("00000000000000000000000000000194").thenReturn("1234");
    when(servletRequest.getPathInfo()).thenReturn("/path");
    when(servletRequest.getSession()).thenReturn(httpSession);
    when(httpSession.getId()).thenReturn("1234");
    when(authenticationManager.authenticate(any(Authentication.class))).thenReturn(authResult);

    when(authResult.getPrincipal()).thenReturn(paasUser);

    openStackAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain);
}

From source file:net.sf.sail.webapp.presentation.web.filters.PasAuthenticationProcessingFilter.java

/**
 * @see org.acegisecurity.ui.AbstractProcessingFilter#successfulAuthentication(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse,
 *      org.acegisecurity.Authentication)
 *///from w ww .j  av a 2  s. c  om
@Override
protected void successfulAuthentication(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response, Authentication authResult)
        throws IOException, ServletException {

    UserDetails userDetails = (UserDetails) authResult.getPrincipal();
    if (LOGGER.isDebugEnabled()) {
        logDebug(userDetails);
    }

    HttpSession session = request.getSession();
    ApplicationContext springContext = WebApplicationContextUtils
            .getWebApplicationContext(session.getServletContext());
    UserService userService = (UserService) springContext.getBean("userService");
    User user = userService.retrieveUser(userDetails);
    session.setAttribute(User.CURRENT_USER_SESSION_KEY, user);

    // add new session in a allLoggedInUsers servletcontext HashMap variable
    String sessionId = session.getId();
    HashMap<String, User> allLoggedInUsers = (HashMap<String, User>) session.getServletContext()
            .getAttribute("allLoggedInUsers");
    if (allLoggedInUsers == null) {
        allLoggedInUsers = new HashMap<String, User>();
        session.getServletContext().setAttribute(PasSessionListener.ALL_LOGGED_IN_USERS, allLoggedInUsers);
    }
    allLoggedInUsers.put(sessionId, user);

    super.successfulAuthentication(request, response, authResult);
}

From source file:org.apache.stratos.rest.endpoint.mock.StratosApiV40Mock.java

@GET
@Path("/cookie")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response getCookie() {
    HttpSession httpSession = httpServletRequest.getSession(true);//create session if not found
    String sessionId = httpSession.getId();
    return Response.ok().header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
            .entity(Utils.buildAuthenticationSuccessMessage(sessionId)).build();
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

/** Obtains the session ID from the request, or "unknown" if no session pressent. */
public static String getSessionId(HttpServletRequest request) {
    HttpSession session = request.getSession();
    return (session == null ? "unknown" : session.getId());
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private String getAuthenticationEndPoint(final HttpServletRequest httpRequest, final Token token,
        final Boolean isError) {
    if (httpRequest == null) {
        throw new PreconditionException("Required parameter is null");
    }//from w  ww  .  j  av  a 2s .com
    try {
        final String requestURI = httpRequest.getRequestURI();
        final String queryString = httpRequest.getQueryString();
        final ApplicationSettings applicationSettings = applicationSettingsLoader.load();
        final Configuration configuration = configurationCache.load();
        if (configuration == null) {
            throw new GeneralException("Error loading configuration");
        }
        final HttpSession session = httpRequest.getSession(false);
        final String sessionName = session == null ? "" : session.getId();
        final StringBuilder uriStringBuilder = new StringBuilder();
        Base64 encoder = new Base64();

        if (isError) {
            final State previousState = getState(httpRequest);
            uriStringBuilder.append(previousState.getRequestURI());
        } else {
            uriStringBuilder.append(requestURI);
            if (queryString != null && !"".equals(queryString.trim())) {
                uriStringBuilder.append("?");
                uriStringBuilder.append(queryString);
            }
        }

        final String userID = token == null ? "" : token.getUserID().getValue();
        final State state = stateFactory.createState(userID, sessionName, uriStringBuilder.toString());
        final ObjectMapper mapper = new ObjectMapper();
        final String stateString = mapper.writeValueAsString(state);
        final String urlString = String.format(
                "%s%sclient_Id=%s&state=%s&nonce=defaultNonce&redirect_uri=%s&scope=openid%%20offline_access&response_type=code+id_token&prompt=%s&response_mode=form_post",
                configuration.getAuthenticationEndPoint(),
                configuration.getAuthenticationEndPoint().getName().contains("?") ? "&" : "?",
                applicationSettings.getApplicationId(),
                new String(encoder.encode(stateString.getBytes()), "UTF-8"),
                URLEncoder.encode(applicationSettings.getRedirectURL().getValue(), "UTF-8"),
                token == null ? "login" : "none");
        return urlString;
    } catch (IOException e) {
        throw new GeneralException("IO Exception", e);
    }
}

From source file:org.apache.struts.action.ActivityAction.java

/**
 * Return context, instantiating it if necessary.
 *//* w w  w  . j av a 2 s .co m*/
protected WebContext getContext(ActionMapping mapping, HttpServletRequest request,
        HttpServletResponse response) {

    String contextId = mapping.getParameter();
    HttpSession session = request.getSession();
    WebContext context = (WebContext) session.getAttribute(contextId);
    if (context == null) {
        if (doDebugLog())
            servlet.log("{" + session.getId() + "} Creating new Context");
        context = new WebContext();
        // context.setActivity(getActivity(contextId));
        context.setActivity(activity);
        context.setHttpSession(session);
        context.setServletContext(servlet.getServletContext());
        if (doDebugListener())
            context.addContextListener(this);
        session.setAttribute(contextId, context);
        context.call(context.getActivity());
    }
    return context;

}

From source file:gov.nih.nci.ncicb.cadsr.umlmodelbrowser.servlets.SessionFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, javax.servlet.ServletException {
    String expiredSessionJSP = filterConfig.getInitParameter("expiredSessionJSP");
    HttpServletRequest httpservletrequest = (HttpServletRequest) request;
    HttpSession httpsession = httpservletrequest.getSession(false);
    if (httpsession == null && httpservletrequest.getRequestedSessionId() == null) {
        //This is a client accessing the first time.
        chain.doFilter(request, response);
        return;//w w  w.j  ava 2  s.  c  o m
    }
    if (httpsession == null || httpservletrequest.getRequestedSessionId() == null) {
        ((HttpServletResponse) response).sendRedirect(httpservletrequest.getContextPath() + expiredSessionJSP);
        return;
    } else {
        String s = httpsession.getId();
        if (s.equals(httpservletrequest.getRequestedSessionId())) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response)
                    .sendRedirect(httpservletrequest.getContextPath() + expiredSessionJSP);
            return;
        }
    }
}

From source file:com.rockagen.gnext.service.spring.security.extension.BasicConcurrentSessionControlStrategy.java

/**
 * Check authentication allowed./*from   ww  w.  j  a  v  a2s.co m*/
 * 
 * @param authentication
 *            the authentication
 * @param request
 *            the request
 * @throws AuthenticationException
 *             the authentication exception
 */
private void checkAuthenticationAllowed(Authentication authentication, HttpServletRequest request)
        throws AuthenticationException {

    final List<SessionInformation> sessions = sessionRegistry.getAllSessions(authentication.getPrincipal(),
            false);

    int sessionCount = sessions.size();
    int allowedSessions = getMaximumSessionsForThisUser(authentication);

    if (sessionCount < allowedSessions) {
        // They haven't got too many login sessions running at present
        return;
    }

    if (allowedSessions == -1) {
        // We permit unlimited logins
        return;
    }

    if (sessionCount == allowedSessions) {
        HttpSession session = request.getSession(false);

        if (session != null) {
            // Only permit it though if this request is associated with one of the already registered sessions
            for (SessionInformation si : sessions) {
                if (si.getSessionId().equals(session.getId())) {
                    return;
                }
            }
        }
        // If the session is null, a new one will be created by the parent class, exceeding the allowed number
    }

    BasicPrincipal basicPrincipal = new BasicPrincipal(authentication);
    //
    // verify the ip value in the basicPrincipal
    //
    boolean sameIp = false;
    List<Object> allValidPrincipals = new ArrayList<Object>();
    for (SessionInformation sessionInformation : sessions) {
        allValidPrincipals.add(sessionInformation.getPrincipal());
    }

    for (Object savedPrincipal : allValidPrincipals) {
        if (basicPrincipal.equals(savedPrincipal)) {
            sameIp = basicPrincipal.equalsIp((BasicPrincipal) savedPrincipal);

            break;
        }
    }
    allowableSessionsExceeded(sessions, allowedSessions, sameIp, sessionRegistry);
}

From source file:com.brienwheeler.web.spring.security.SetUserInSessionInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    long userId = SecurityUtils.getLoggedInUserId();

    if (userId != 0) {
        // we have a logged in user, see if the session has the user on it
        HttpSession session = request.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute(SESSION_ATTR_USER);
            if (user == null) {
                user = userService.findById(new DbId<User>(User.class, userId));
                if (user == null)
                    throw new IllegalStateException("failed to lookup authenticated user");
                else {
                    log.info("setting user id " + user.getId() + " into session " + session.getId());
                    session.setAttribute(SESSION_ATTR_USER, user);
                }/* ww  w .  ja v a  2  s.c  o m*/
            } else if (user.getId() != userId)
                throw new IllegalStateException("id of stored user does not match current authenticated user");
        }
    }

    return super.preHandle(request, response, handler);
}

From source file:de.jwic.base.JWicRuntime.java

/**
 * Creates a new SessionContext with the application bean specified in the
 * appProperties argument. The appProperties must contain the name and beanId
 * of the application control./*from  w  w w  .j  a  va  2s  . co  m*/
 * 
 * Sample:<br>
 * <pre> appid=myapp.id
 *  name=app
 *  control=myapp.AppControl </pre>
 * 
 * The request argument is optional. It can be <code>null</code> if you are creating an
 * Application for test cases. In this case, the session is always handled as multisession.
 * 
 * @param appProperties
 * @return
 */
public SessionContext createSessionContext(IApplicationSetup appSetup, Locale locale, TimeZone timeZone,
        HttpServletRequest request) {

    HttpSession session = request != null ? request.getSession() : null;
    String clientID = session != null ? session.getId() : "test"; // testenvironment

    if (session != null && session.getAttribute(ATTR_NOTIFIER) == null) {
        // Add a "listener" so we know when the session is closed.
        session.setAttribute(ATTR_NOTIFIER, new HttpSessionClosedListener(this, session.getId()));
    }

    SessionContext sc = null;
    if (appSetup.isSingleSession() && session != null) {
        SessionContainer container = sessionManager.getByAppID(clientID, appSetup.getName());
        if (container == null) {
            sc = setupSessionContext(appSetup, locale, timeZone, request);
        } else {
            // notify the session that it has been "reused"
            if (container.getState() == SessionContainer.STATE_STORED) {
                sessionManager.deserialize(container);
            }
            container.access();
            sc = container.getSessionContext();
            sc.fireEvent(new SessionEvent(Compatibility.getParameterMap(request)),
                    SessionContext.SESSION_REUSED);
        }

    } else {
        sc = setupSessionContext(appSetup, locale, timeZone, request);
    }

    return sc;
}