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.deep.two.authority.impl.FareAbstractSessionFixationProtection.java

/**
 * Called when a user is newly authenticated.
 * <p>//from  w ww.  j a v a2 s  .  com
 * If a session already exists, and matches the session Id from the client,
 * a new session will be created, and the session attributes copied to it
 * (if {@code migrateSessionAttributes} is set). If the client's requested
 * session Id is invalid, nothing will be done, since there is no need to
 * change the session Id if it doesn't match the current session.
 * <p>
 * If there is no session, no action is taken unless the
 * {@code alwaysCreateSession} property is set, in which case a session will
 * be created if one doesn't already exist.
 */
public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) {
    /*String queryString = request.getQueryString();
    String userName = "";
            
    if (queryString != null) {
    int index = queryString.indexOf("userName=");
    if (index != -1) {
        userName = queryString.substring(index + 9);
    }
    } else {
    userName = request.getParameter("j_username");
    }
    HttpSession session = SessionHelper.sessionMap.get(userName);*/

    boolean hadSessionAlready = request.getSession(false) != null;

    if (!hadSessionAlready && !alwaysCreateSession) {
        // Session fixation isn't a problem if there's no session
        return;
    }
    // Create new session if necessary
    HttpSession session = request.getSession();

    if (hadSessionAlready && request.isRequestedSessionIdValid()) {
        String originalSessionId;
        String newSessionId;
        Object mutex = WebUtils.getSessionMutex(session);
        synchronized (mutex) {
            // We need to migrate to a new session
            originalSessionId = session.getId();

            session = applySessionFixation(session, request);
            newSessionId = session.getId();
        }

        if (originalSessionId.equals(newSessionId)) {
            logger.warn(
                    "Your servlet container did not change the session ID when a new session was created. You will"
                            + " not be adequately protected against session-fixation attacks");
        }
        onSessionChange(originalSessionId, session, authentication);
    }
}

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

public static void startSignatureJson(HttpServletRequest request, HttpServletResponse response,
        ServletContext context, byte[] pdfData, String connector, String position, String transactionId,
        String profile, Map<String, String> preProcessor, Map<String, String> overwrite) throws Exception {

    // TODO: Protect session so that only one PDF can be signed during one
    // session/*from  w  w  w  .j  ava 2 s  . com*/
    /*
     * if(PdfAsHelper.isSignatureActive(request)) { throw new
     * PdfAsException("Signature is active in this session"); }
     *
     * PdfAsHelper.setSignatureActive(request, true);
     */

    validatePdfSize(request, response, pdfData);

    HttpSession session = request.getSession();

    logger.info("Starting signature in session: " + session.getId());

    Configuration config = pdfAs.getConfiguration();
    session.setAttribute(PDF_CONFIG, config);

    ConfigurationOverwrite.overwriteConfiguration(overwrite, config);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    session.setAttribute(PDF_OUTPUT, baos);

    // Generate Sign Parameter
    SignParameter signParameter = PdfAsFactory.createSignParameter(config, new ByteArrayDataSource(pdfData),
            baos);

    logger.info("Setting TransactionID: " + transactionId);

    signParameter.setTransactionId(transactionId);

    IPlainSigner signer;
    if (connector.equals("bku") || connector.equals("onlinebku") || connector.equals("mobilebku")) {
        BKUSLConnector conn = new BKUSLConnector(config);
        // conn.setBase64(true);
        signer = new PAdESSigner(conn);
        session.setAttribute(PDF_SL_CONNECTOR, conn);
    } else {
        throw new PdfAsWebException("Invalid connector (bku | onlinebku | mobilebku | moa | jks)");
    }
    signParameter.setPreprocessorArguments(preProcessor);
    signParameter.setPlainSigner(signer);
    session.setAttribute(PDF_SIGNER, signer);
    session.setAttribute(PDF_SL_INTERACTIVE, connector);

    String qrCodeContent = PdfAsHelper.getQRCodeContent(request);

    if (qrCodeContent != null) {
        if (profile == null) {
            // get default Profile
            profile = config.getValue("sig_obj.type.default");
        }

        if (profile == null) {
            logger.warn("Failed to determine default profile! Using hard coded!");
            profile = "SIGNATURBLOCK_SMALL_DE";
        }

        ByteArrayOutputStream qrbaos = new ByteArrayOutputStream();
        try {
            String key = "sig_obj." + profile + ".value.SIG_LABEL";
            QRCodeGenerator.generateQRCode(qrCodeContent, qrbaos, 200);
            String value = Base64.encodeBase64String(qrbaos.toByteArray());
            config.setValue(key, value);
        } finally {
            IOUtils.closeQuietly(qrbaos);
        }
    }

    // set Signature Profile (null use default ...)
    signParameter.setSignatureProfileId(profile);

    // set Signature Position
    signParameter.setSignaturePosition(position);

    StatusRequest statusRequest = pdfAs.startSign(signParameter);
    session.setAttribute(PDF_STATUS, statusRequest);
}

From source file:com.github.dactiv.fear.user.service.account.AccountService.java

/**
 * ?//from  w w  w  .  j  ava 2  s  .  c o  m
 *
 * @param username ??
 * @param captcha ??
 */
public Map<String, Object> forgotPassword(String username, String captcha) throws Exception {

    HttpSession session = (HttpSession) RequestContextHolder.currentRequestAttributes().getSessionMutex();
    captchaManager.setCurrentSession(session);

    ValidResult validResult = captchaManager.valid(session.getId(), captcha);

    if (validResult.getIsValid()) {
        throw new ServiceException(validResult.getMessage());
    }

    Map<String, Object> user = Apis.invoke("accountService", "getUserByUsernameOrEmail", username);

    if (MapUtils.isEmpty(user)) {
        throw new ServiceException("?[" + username + "]");
    }

    sendForgetPasswordMail(user);

    return user;
}

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

public static void startSignature(HttpServletRequest request, HttpServletResponse response,
        ServletContext context, byte[] pdfData, String connector, String position, String transactionId,
        String profile, Map<String, String> preProcessor, Map<String, String> overwrite) throws Exception {

    // TODO: Protect session so that only one PDF can be signed during one
    // session/*from   w w w .j  av a  2 s  .  c  o m*/
    /*
     * if(PdfAsHelper.isSignatureActive(request)) { throw new
     * PdfAsException("Signature is active in this session"); }
     * 
     * PdfAsHelper.setSignatureActive(request, true);
     */

    validatePdfSize(request, response, pdfData);

    HttpSession session = request.getSession();

    logger.info("Starting signature in session: " + session.getId());

    Configuration config = pdfAs.getConfiguration();
    session.setAttribute(PDF_CONFIG, config);

    ConfigurationOverwrite.overwriteConfiguration(overwrite, config);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    session.setAttribute(PDF_OUTPUT, baos);

    // Generate Sign Parameter
    SignParameter signParameter = PdfAsFactory.createSignParameter(config, new ByteArrayDataSource(pdfData),
            baos);

    logger.info("Setting TransactionID: " + transactionId);

    signParameter.setTransactionId(transactionId);

    IPlainSigner signer;
    if (connector.equals("bku") || connector.equals("onlinebku") || connector.equals("mobilebku")) {
        BKUSLConnector conn = new BKUSLConnector(config);
        // conn.setBase64(true);
        signer = new PAdESSigner(conn);
        session.setAttribute(PDF_SL_CONNECTOR, conn);
    } else {
        throw new PdfAsWebException("Invalid connector (bku | onlinebku | mobilebku | moa | jks)");
    }
    signParameter.setPreprocessorArguments(preProcessor);
    signParameter.setPlainSigner(signer);
    session.setAttribute(PDF_SIGNER, signer);
    session.setAttribute(PDF_SL_INTERACTIVE, connector);

    String qrCodeContent = PdfAsHelper.getQRCodeContent(request);

    if (qrCodeContent != null) {
        if (profile == null) {
            // get default Profile
            profile = config.getValue("sig_obj.type.default");
        }

        if (profile == null) {
            logger.warn("Failed to determine default profile! Using hard coded!");
            profile = "SIGNATURBLOCK_SMALL_DE";
        }

        ByteArrayOutputStream qrbaos = new ByteArrayOutputStream();
        try {
            String key = "sig_obj." + profile + ".value.SIG_LABEL";
            QRCodeGenerator.generateQRCode(qrCodeContent, qrbaos, 200);
            String value = Base64.encodeBase64String(qrbaos.toByteArray());
            config.setValue(key, value);
        } finally {
            IOUtils.closeQuietly(qrbaos);
        }
    }

    // set Signature Profile (null use default ...)
    signParameter.setSignatureProfileId(profile);

    // set Signature Position
    signParameter.setSignaturePosition(position);

    StatusRequest statusRequest = pdfAs.startSign(signParameter);
    session.setAttribute(PDF_STATUS, statusRequest);

    PdfAsHelper.process(request, response, context);
}

From source file:org.apache.accumulo.monitor.servlets.ShellServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Verify that this is the active Monitor instance
    if (!isActiveMonitor()) {
        resp.sendError(HttpURLConnection.HTTP_UNAVAILABLE, STANDBY_MONITOR_MESSAGE);
        return;//from   ww w . j a v  a 2s.c  om
    }
    final HttpSession session = req.getSession(true);
    String user = (String) session.getAttribute("user");
    if (user == null || !userShells().containsKey(session.getId())) {
        // no existing shell for user, re-authenticate
        doGet(req, resp);
        return;
    }
    final String CSRF_TOKEN = (String) session.getAttribute(CSRF_KEY);
    if (null == CSRF_TOKEN) {
        // no csrf token, need to re-auth
        doGet(req, resp);
    }
    ShellExecutionThread shellThread = userShells().get(session.getId());
    String cmd = req.getParameter("cmd");
    if (cmd == null) {
        // the command is null, just print prompt
        resp.getWriter().append(shellThread.getPrompt());
        resp.getWriter().flush();
        return;
    }
    shellThread.addInputString(cmd);
    shellThread.waitUntilReady();
    if (shellThread.isDone()) {
        // the command was exit, invalidate session
        userShells().remove(session.getId());
        session.invalidate();
        return;
    }
    // get the shell's output
    StringBuilder sb = new StringBuilder();
    sb.append(shellThread.getOutput().replace("<", "&lt;").replace(">", "&gt;"));
    if (sb.length() == 0 || !(sb.charAt(sb.length() - 1) == '\n'))
        sb.append("\n");
    // check if shell is waiting for input
    if (!shellThread.isWaitingForInput())
        sb.append(shellThread.getPrompt());
    // check if shell is waiting for password input
    if (shellThread.isMasking())
        sb.append("*");
    resp.getWriter().append(sb.toString());
    resp.getWriter().flush();
}

From source file:edu.harvard.i2b2.fhirserver.ws.OAuth2AuthzEndpoint.java

String successfulResponse(HttpServletRequest request)
        throws OAuthSystemException, URISyntaxException, OAuthProblemException {
    OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
    OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

    String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);

    OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request,
            HttpServletResponse.SC_FOUND);

    String redirectURI = oauthRequest.getRedirectURI();

    if (responseType.equals(ResponseType.CODE.toString())) {
        String authorizationCode = oauthIssuerImpl.authorizationCode();

        logger.info("generated authorizationCode:" + authorizationCode);
        builder.setCode(authorizationCode);
        builder.setParam("state", oauthRequest.getState());

        HttpSession session = request.getSession();
        session.setAttribute("authorizationCode", authorizationCode);
        logger.info("put generated authcode " + session.getAttribute("authorizationCode") + " in session "
                + session.getId());

    }//from   w  w w  .  j  a va 2s.com
    final OAuthResponse Oresponse = builder.location(redirectURI).buildQueryMessage();
    URI url = new URI(Oresponse.getLocationUri());

    return url.toString();
}

From source file:fr.paris.lutece.plugins.directory.business.AbstractEntryTypeUpload.java

/**
 * Get the file source from the session//  ww  w.  j ava 2 s . co  m
 * @param request the HttpServletRequest
 * @return the file item
 */
protected List<FileItem> getFileSources(HttpServletRequest request) {
    HttpSession session = request.getSession(false);

    if (session != null) {
        // check the file in session - it might no be deleted
        return DirectoryAsynchronousUploadHandler.getHandler().getFileItems(Integer.toString(getIdEntry()),
                session.getId());
    }

    return null;
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.localepairs.LocalePairImportHandler.java

public void invokePageHandler(WebPageDescriptor p_pageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    String sessionId = session.getId();
    SessionManager sessionMgr = (SessionManager) session.getAttribute(WebAppConstants.SESSION_MANAGER);
    String companyId = CompanyThreadLocal.getInstance().getValue();
    boolean isSuperAdmin = ((Boolean) session.getAttribute(WebAppConstants.IS_SUPER_ADMIN)).booleanValue();

    String action = p_request.getParameter("action");
    try {/*from w  w  w  . j av  a  2  s  .  co  m*/
        if (LocalePairConstants.IMPORT.equals(action)) {
            if (isSuperAdmin) {
                importLocalePair(p_request);
                p_request.setAttribute("currentId", companyId);
            }
        } else if ("startUpload".equals(action)) {
            File uploadedFile = this.uploadFile(p_request);
            if (isSuperAdmin) {
                String importToCompId = p_request.getParameter("companyId");
                session.setAttribute("importToCompId", importToCompId);
            }
            session.setAttribute("uploading_filter", uploadedFile);
        } else if ("doImport".equals(action)) {
            int count = 0;
            if (sessionMgr.getAttribute("count") != null) {
                count = (Integer) sessionMgr.getAttribute("count");
                if (count == 1) {
                    count++;
                    sessionMgr.setAttribute("count", count);
                }
            } else {
                count++;
                sessionMgr.setAttribute("count", count);
            }
            if (session.getAttribute("uploading_filter") != null) {
                filter_percentage_map.clear();// .remove(sessionId);
                filter_error_map.clear();// .remove(sessionId);
                File uploadedFile = (File) session.getAttribute("uploading_filter");
                String importToCompId = (String) session.getAttribute("importToCompId");

                session.removeAttribute("importToCompId");
                session.removeAttribute("uploading_filter");
                DoImport imp = new DoImport(sessionId, uploadedFile, companyId, importToCompId);
                imp.start();
            } else {
                logger.error("No uploaded user info file.");
            }
        } else if ("refreshProgress".equals(action)) {
            this.refreshProgress(p_request, p_response, sessionId);
            return;
        }
    } catch (RemoteException re) {
        throw new EnvoyServletException(EnvoyServletException.EX_GENERAL, re);
    } catch (GeneralException ge) {
        throw new EnvoyServletException(EnvoyServletException.EX_GENERAL, ge);
    }
    super.invokePageHandler(p_pageDescriptor, p_request, p_response, p_context);
}

From source file:com.sunchenbin.store.feilong.servlet.http.builder.RequestLogBuilder.java

/**
 * ?./*  w ww. j  a  va  2 s.  c  o  m*/
 * 
 * <p>
 * ?log, Cannot create a session after the response has been committed <br>
 * 
 * </p>
 * 
 * <p>
 * I have learnt that maybe my 8K buffer gets full in some cases (as you said, my contect is dynamic and sometimes could be large). <br>
 * 
 * In that case, I have understanded that a full buffer triggers a commit, and when that happens the JSP error page can not do its job
 * and then "java.lang.IllegalStateException: Cannot create a session after the response has been committed" happens. <br>
 * 
 * OK, but is there any other possible reason for the early commit? <br>
 * My session is created early enough, and in fact the JSP page creates it if necessary, by default.
 * </p>
 *
 * @return the session id,,  {@link java.lang.Throwable#getMessage()}
 * @since 1.4.1
 */
private String getSessionId() {
    try {
        HttpSession session = request.getSession(false);
        return null == session ? StringUtils.EMPTY : session.getId();
    } catch (IllegalStateException e) {//Cannot create a session after the response has been committed 
        String msg = Slf4jUtil.formatMessage("uri:[{}],paramMap:{}", request.getRequestURI(),
                request.getParameterMap());
        LOGGER.error(msg, e);
        return e.getMessage();
    }
}

From source file:jeeves.server.sources.http.JeevesServlet.java

private void execute(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String ip = req.getRemoteAddr();
    // if we do have the optional x-forwarded-for request header then
    // use whatever is in it to record ip address of client
    String forwardedFor = req.getHeader("x-forwarded-for");
    if (forwardedFor != null)
        ip = forwardedFor;/*from   w w w  .  jav a2 s. c o m*/

    Log.info(Log.REQUEST, "==========================================================");
    Log.info(Log.REQUEST, "HTML Request (from " + ip + ") : " + req.getRequestURI());
    if (Log.isDebugEnabled(Log.REQUEST)) {
        Log.debug(Log.REQUEST, "Method       : " + req.getMethod());
        Log.debug(Log.REQUEST, "Content type : " + req.getContentType());
        //      Log.debug(Log.REQUEST, "Context path : "+ req.getContextPath());
        //      Log.debug(Log.REQUEST, "Char encoding: "+ req.getCharacterEncoding());
        Log.debug(Log.REQUEST, "Accept       : " + req.getHeader("Accept"));
        //      Log.debug(Log.REQUEST, "Server name  : "+ req.getServerName());
        //      Log.debug(Log.REQUEST, "Server port  : "+ req.getServerPort());
    }
    //      for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
    //         String theHeader = (String)e.nextElement();
    //        if(Log.isDebugEnabled(Log.REQUEST)) {
    //         Log.debug(Log.REQUEST, "Got header: "+theHeader);   
    //         Log.debug(Log.REQUEST, "With value: "+req.getHeader(theHeader));
    //        }
    //      }
    HttpSession httpSession = req.getSession();
    if (Log.isDebugEnabled(Log.REQUEST))
        Log.debug(Log.REQUEST, "Session id is " + httpSession.getId());
    UserSession session = (UserSession) httpSession.getAttribute("session");

    //------------------------------------------------------------------------
    //--- create a new session if doesn't exist

    if (session == null) {
        //--- create session

        session = new UserSession();
        httpSession.setAttribute("session", session);
        if (Log.isDebugEnabled(Log.REQUEST))
            Log.debug(Log.REQUEST, "Session created for client : " + ip);
    }

    session.setProperty("realSession", httpSession);
    //------------------------------------------------------------------------
    //--- build service request

    ServiceRequest srvReq = null;

    //--- create request

    try {
        srvReq = ServiceRequestFactory.create(req, res, jeeves.getUploadDir(), jeeves.getMaxUploadSize());
    } catch (FileUploadTooBigEx e) {
        StringBuffer sb = new StringBuffer();
        sb.append("Opgeladen bestand overschrijdt de maximaal toegelaten grootte van "
                + jeeves.getMaxUploadSize() + " Mb\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    } catch (FileTypeNotAllowedEx e) {
        StringBuffer sb = new StringBuffer();
        sb.append("Bestand heeft niet het juiste type\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    } catch (Exception e) {
        StringBuffer sb = new StringBuffer();

        sb.append("Cannot build ServiceRequest\n");
        sb.append("Cause : " + e.getMessage() + "\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    }

    if ("user.agiv.login".equals(srvReq.getService())) {
        if (srvReq.getParams() != null && srvReq.getParams().getChild("wa") != null
                && srvReq.getParams().getChild("wa").getTextTrim().equals("wsignoutcleanup1.0")) {
            srvReq.setService("user.agiv.logout");
        } else {
            Principal p = req.getUserPrincipal();
            if (p != null
                    && p instanceof FederationPrincipal/* && SecurityTokenThreadLocal.getToken()==null*/) {
                FederationPrincipal fp = (FederationPrincipal) p;
                /*
                                  for (Claim c: fp.getClaims()) {
                                      System.out.println(c.getClaimType().toString() + ":" + (c.getValue()!=null ? c.getValue().toString() : ""));               
                                  }
                */
                Map<String, String> roleProfileMapping = new HashMap<String, String>();
                String profile = null;
                roleProfileMapping.put("Authenticated", "RegisteredUser");
                roleProfileMapping.put(nodeType + " Metadata Admin", "Administrator");
                roleProfileMapping.put(nodeType + " Metadata Editor", "Editor");
                roleProfileMapping.put(nodeType + " Metadata Hoofdeditor", "Hoofdeditor");
                List<String> roleListToCheck = Arrays.asList(nodeType + " Metadata Admin",
                        nodeType + " Metadata Hoofdeditor", nodeType + " Metadata Editor", "Authenticated");
                for (String item : roleListToCheck) {
                    if (req.isUserInRole(item)) {
                        profile = roleProfileMapping.get(item);
                        break;
                    }
                }
                String contactid = Util.getClaimValue(fp, "contactid");
                session.authenticate(contactid, contactid/* + "_" + Util.getClaimValue(fp,"name")*/,
                        Util.getClaimValue(fp, "givenname"), Util.getClaimValue(fp, "surname"),
                        profile != null ? profile : "RegisteredUser", Util.getClaimValue(fp, "emailaddress"));
                List<Map<String, String>> groups = new ArrayList<Map<String, String>>();
                Map<String, String> group = new HashMap<String, String>();
                String parentorganisationid = Util.getClaimValue(fp, "parentorganisationid");
                String parentorganisationdisplayname = Util.getClaimValue(fp, "parentorganisationdisplayname");
                group.put("name",
                        StringUtils.isBlank(parentorganisationid) ? Util.getClaimValue(fp, "organisationid")
                                : parentorganisationid);
                group.put("description",
                        StringUtils.isBlank(parentorganisationdisplayname)
                                ? (StringUtils.isBlank(parentorganisationid)
                                        ? Util.getClaimValue(fp, "organisationdisplayname")
                                        : parentorganisationid)
                                : parentorganisationdisplayname);
                groups.add(group);
                session.setProperty("groups", groups);
            } else {
                System.out.println("Principal is not instance of FederationPrincipal");
            }
        }
    }

    //--- execute request

    jeeves.dispatch(srvReq, session);
}