示例#1
1
  public static void showSession(HttpServletRequest req, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    out.println("Session id: " + session.getId());
    out.println(" session.isNew(): " + session.isNew());
    out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
    out.println(
        " session.getCreationTime(): "
            + session.getCreationTime()
            + " ("
            + new Date(session.getCreationTime())
            + ")");
    out.println(
        " session.getLastAccessedTime(): "
            + session.getLastAccessedTime()
            + " ("
            + new Date(session.getLastAccessedTime())
            + ")");
    out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
    out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
    out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());

    out.println("Saved session Attributes:");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
    }
  }
示例#2
1
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {

      String target = ((HttpServletRequest) request).getRequestURI();

      HttpSession session = ((HttpServletRequest) request).getSession();

      if (session == null) {
        /* まだ認証されていない */
        session = ((HttpServletRequest) request).getSession(true);
        session.setAttribute("target", target);
        ((HttpServletResponse) response).sendRedirect("/refrigerator/LoginPage");
      } else {
        Object loginCheck = session.getAttribute("login");
        if (loginCheck == null) {
          /* まだ認証されていない */
          session.setAttribute("target", target);
          ((HttpServletResponse) response).sendRedirect("/refrigerator/LoginPage");
        }
      }

      chain.doFilter(request, response);

    } catch (ServletException se) {
    } catch (IOException e) {
    }
  }
  /**
   * Creates a Discussion Post
   *
   * <p>- Requires a cookie for the session user - Requires a comment and threadId request parameter
   * for the POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void createPostAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<>();

    if (req.getMethod() == HttpMethod.Post) {
      DiscussionManager dm = new DiscussionManager();

      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");

      // Create the discussion post
      DiscussionPost post = new DiscussionPost();
      post.setUserId(userSession.getUserId());
      post.setMessage(req.getParameter("comment"));
      post.setThreadId(Integer.parseInt(req.getParameter("threadId")));

      dm.createPost(post);

      redirectToLocal(req, res, "/group/discussion/?threadId=" + req.getParameter("threadId"));
    } else {
      httpNotFound(req, res);
    }
  }
示例#4
1
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.print("<html><head><title>Page2</title></head><body>");
    Users tmpUser = null;
    HttpSession session;

    tmpUser = usersService.findByLogin(request.getParameter("login"));
    if (tmpUser != null) {
      if ((tmpUser.getPassword()).equals(request.getParameter("password"))) {
        session = request.getSession(true);
        session.setAttribute("users", tmpUser);
        response.sendRedirect("http://localhost:8080/orders");
      } else {
        out.print("Access denied :(");
      }

    } else {
      String login = request.getParameter("login");
      String pass = request.getParameter("password");
      tmpUser = new Users(login, pass);
      usersService.saveUsers(tmpUser);
      session = request.getSession(true);
      session.setAttribute("users", tmpUser);
      response.sendRedirect("http://localhost:8080/orders");
    }
    out.print("</body></html>");
  }
  private void processReturn(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Account principal = this.verifyResponse(req);

    // System.out.println(principal);

    String returnURL = req.getParameter("exist_return");

    if (principal == null) {
      // this.getServletContext().getRequestDispatcher("/openid/login.xql").forward(req, resp);
      resp.sendRedirect(returnURL);
    } else {
      HttpSession session = req.getSession(true);

      // ((XQueryURLRewrite.RequestWrapper)req).setUserPrincipal(principal);

      Subject subject = new Subject();

      // TODO: hardcoded to jetty - rewrite
      // *******************************************************
      DefaultIdentityService _identityService = new DefaultIdentityService();
      UserIdentity user = _identityService.newUserIdentity(subject, principal, new String[0]);

      Authentication cached = new HttpSessionAuthentication(session, user);
      session.setAttribute(HttpSessionAuthentication.__J_AUTHENTICATED, cached);
      // *******************************************************

      resp.sendRedirect(returnURL);
    }
  }
  /**
   * Deletes a meeting from the database
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    if (req.getMethod() == HttpMethod.Get) {

      // Get the meeting
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      MeetingManager meetingMan = new MeetingManager();
      Meeting meeting = meetingMan.get(meetingId);
      meetingMan.deleteMeeting(meetingId);

      // Update the User Session to remove meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      List<Meeting> adminMeetings = userSession.getUser().getMeetings();

      for (int i = 0; i < adminMeetings.size(); i++) {
        Meeting m = adminMeetings.get(i);
        if (m.getId() == meeting.getId()) {
          adminMeetings.remove(i);
          break;
        }
      }

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } else if (req.getMethod() == HttpMethod.Post) {
      httpNotFound(req, res);
    }
  }
 public void service(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   HttpSession sess = req.getSession(false);
   sess.invalidate();
   System.out.println("Session Closed");
   res.sendRedirect("index.html");
 }
示例#8
0
  /**
   * Parse the case id from the url and then delete it. Finally redirects the response and the
   * request to admCase.jsp
   *
   * @see DatabaseMethods#caseDelete(int)
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    DatabaseMethods dbPoint = new DatabaseMethods();
    HttpSession userSession = request.getSession();

    if (Integer.parseInt(userSession.getAttribute("isadmin").toString()) == 1) {
      int caseId = Integer.parseInt(request.getParameter("caseId"));

      int success = dbPoint.caseDelete(caseId);

      if (success != 0) {
        userSession.setAttribute("caseDelete", "1");
      } else {
        userSession.setAttribute("caseDelete", "0");
      }
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/admCase.jsp");
    if (rd != null) {
      rd.forward(request, response);
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    String amount = request.getParameter("amount");
    String amount2 = request.getParameter("amount2");
    String amount3 = request.getParameter("amount3");
    Integer posotita = Integer.parseInt(amount);
    Integer posotita2 = Integer.parseInt(amount2);
    Integer posotita3 = Integer.parseInt(amount3);

    HttpSession session = request.getSession();

    if (session.isNew()) {
      request.setAttribute("sessionVal", "this is a new session");
    } else {
      request.setAttribute("sessionVal", "Welcome Back!");
    }

    double total = ((posotita * 18.50) + (posotita2 * 6.95) + (posotita3 * 1.29));
    session.setAttribute("totalVal", total);

    request.setAttribute("currency", total);
    request.setAttribute("from", amount);
    request.setAttribute("from2", amount2);
    request.setAttribute("from3", amount3);

    RequestDispatcher view = request.getRequestDispatcher("index.jsp");
    view.forward(request, response);
  }
示例#10
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    String support = "support"; // valid username

    HttpSession session = null;
    session = req.getSession(false); // Get user's session object (no new one)
    if (session == null) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String userName = (String) session.getAttribute("user"); // get username

    if (!userName.equals(support)) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String action = "";
    if (req.getParameter("todo") != null) action = req.getParameter("todo");

    if (action.equals("update")) {

      doUpdate(out);
      return;
    }

    out.println("<p>Nothing to do.</p>todo=" + action);
  }
  /* good2() reverses the bodies in the if statement */
  private void good2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    if (IO.static_returns_t()) {
      Logger tcLog = Logger.getLogger("cwe_testcases_logger");
      if (request.getParameter("username") == null) {
        return;
      }
      String username = request.getParameter("username");
      if (username.matches("[a-zA-Z0-9]*")) {
        HttpSession session = request.getSession(true);
        /* FIX: logged message does not contain session id */
        tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId());
      } else {
        response.getWriter().println("Invalid characters");
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Logger tcLog = Logger.getLogger("cwe_testcases_logger");
      if (request.getParameter("username") == null) {
        return;
      }

      String username = request.getParameter("username");

      if (username.matches("[a-zA-Z0-9]*")) {
        HttpSession session = request.getSession(true);
        /* FLAW: leak session ID to debug log */
        tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId());
      } else {
        response.getWriter().println("Invalid characters");
      }
    }
  }
示例#12
0
  /**
   * Validates the login. Writes the isValid flag into the session along with the current user.
   *
   * @return true if OK, false if there's a problem
   */
  private boolean validateLogin(
      HttpSession session, HttpServletRequest req, HttpServletResponse res) throws Exception {

    // Creates a user database access bean.
    UserManager userManager = new UserManager();
    // (no setSession() here, since user may not exist yet)

    // Validates the login
    String username = req.getParameter("Username");
    String password = req.getParameter("Password");
    boolean isValid = userManager.isValidUser(username, password);
    boolean isAdmin = userManager.isAdmin(username);

    // To allow bootstrapping the system, if there are no users
    // yet, set this session valid, and grant admin privileges.
    if (userManager.getRecords().isEmpty()) {
      isValid = true;
      isAdmin = true;
    }

    if (isValid) {
      // Writes User object and validity flag to the session
      session.setAttribute("user", new User(username, password, isAdmin));
      session.setAttribute("isValid", new Boolean(isValid));
    } else {
      Util.putMessagePage(res, "Invalid user or password");
      return false;
    }
    return isValid;
  }
  public static void afterRoot(
      FacesContext context, HttpServletRequest req, HttpServletResponse res) {
    HttpSession session = ((HttpServletRequest) req).getSession(false);

    if (session != null)
      session.setAttribute(ViewHandler.CHARACTER_ENCODING_KEY, res.getCharacterEncoding());
  }
示例#14
0
 /**
  * Adds pair of session and user to the map of active users.
  *
  * @param session the session
  * @param user the user
  */
 public void add(final HttpSession session, final String user) {
   session.setAttribute("User", user);
   session.setAttribute("UserManager", this);
   this.users.put(session, user);
   System.out.println("Login: "******"Logged in users: " + this.users.size());
 }
  public Event perform(HttpServletRequest request) throws HTMLActionException {

    HttpSession session = request.getSession();
    // look up the adventure transportation
    AdventureComponentManager acm =
        (AdventureComponentManager) session.getAttribute(AdventureKeys.COMPONENT_MANAGER);
    Cart cart = acm.getCart(session);
    String origin = request.getParameter("origin");
    // if we are doing a search for a different flight from the cart page
    if (origin == null) {
      origin = cart.getOrigin();
    } else {
      cart.setOrigin(origin);
    }

    String noTransport = request.getParameter("no_transport");
    String showTransport = request.getParameter("show_flights");
    Locale locale = new Locale("en", "us");
    String destination = cart.getDestination();
    // access catalog component and retrieve data from the database
    List transpDepartureBeans = searchTransportation(origin, destination, locale);
    List transpReturnBeans = searchTransportation(destination, origin, locale);

    // places result bean data in the request
    request.setAttribute("departure_result", transpDepartureBeans);
    request.setAttribute("return_result", transpReturnBeans);
    request.setAttribute("search_target", "transportation");
    return null;
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      /*String n=request.getParameter("username");
      out.print("Welcome "+n);*/

      String name = request.getParameter("name");
      String dob = request.getParameter("dob");
      String address = request.getParameter("address");
      String email = request.getParameter("email");
      HttpSession session = request.getSession(true);
      String userid = (String) session.getAttribute("theName");
      int AccNo = 0;
      String AccMsg = "";

      DbCommunication db_comm = new DbCommunication();
      AccNo = db_comm.accountCreation(name, dob, address, email, userid);
      // db_comm.accountCreation(name,email);
      AccMsg = "Account created successfully. Account number is:" + AccNo;
      // out.println(AccMsg);

      String redirectURL = "accountCreationPage.jsp";
      response.sendRedirect(redirectURL);
      session.setAttribute("AccCreationalMsgStatus", "set");
      session.setAttribute("AccCreationalMsg", AccMsg);

    } catch (Exception e) {
      System.out.println(e);
    }
  }
  /**
   * Method execute
   *
   * @param ActionMapping mapping
   * @param ActionForm form
   * @param HttpServletRequest request
   * @param HttpServletResponse response
   * @return ActionForward
   * @throws Exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    HttpSession session = request.getSession();
    // clientXML = (XMLClient) session.getAttribute("client");
    clientXML = XMLClient.getInstance();
    sessionLogin = (String) session.getAttribute("login");

    ajoutsuppressionForm ajoutForm = (ajoutsuppressionForm) form;

    String idperm = ajoutForm.getId1();
    String idrole = ajoutForm.getId2();

    response.setContentType("text/html");

    boolean ajout = clientXML.ajouterPermissionRole(sessionLogin, idperm, idrole);

    if (ajout) {
      String result = "INFO: Permission ajoutée au role";

      session.setAttribute("Resultat", result);
      return mapping.findForward("ok");
    } else {
      String erreur = "ERREUR: Permission non ajoutée au role";

      session.setAttribute("Resultat", erreur);
      return mapping.findForward("failed");
    }
  }
示例#18
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // POST method only used for tracked login operation
    HttpSession session = request.getSession();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Get the username and password from request
    String username = request.getParameter("id");
    String password = request.getParameter("pwd");

    Long id = 0L;
    try {
      id = Long.parseLong(username);
    } catch (Exception ex) {
    }

    if (username != null && password != null) {
      // Login into tracked system
      CTracked ctracked = db.loginTrackedFromMobile(id, password).getResult();

      if (ctracked != null) {
        // Login successful
        out.print("OK," + ctracked.getUsername());
        session.setAttribute("device_id", ctracked.getUsername());
        log.info(ctracked + " : logined!");
      }
    }
  }
 public void doGet(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
     throws IOException, ServletException {
   httpservletresponse.setContentType("text/html");
   PrintWriter printwriter = httpservletresponse.getWriter();
   HttpSession httpsession = httpservletrequest.getSession(true);
   String s = (String) httpsession.getValue("SerapisUser");
   if (s != null && s.length() > 0) {
     printwriter.println("<html>");
     printwriter.println("<head>");
     printwriter.println("</head>");
     printwriter.println("<LINK REL='stylesheet' TYPE='text/css' HREF='../serapis.css'>");
     printwriter.println("<BODY bgcolor='white' leftmargin='0' topmargin='0'>");
     AFunc.cargamenu(printwriter, 1);
     int i = ObtieneDocumentos(printwriter);
     int j = ObtieneDocumentosp(printwriter);
     if (i > 0 || j > 0) {
       printwriter.println(
           "<BR><center><input type='button' name='BtnImprimir' value='Imprimir' class='fondoinput' language='javascript' onclick='window.print()'></center></td>");
     } else {
       printwriter.println("<table border='0' align='center' width='80%'>");
       printwriter.println("<tr>");
       printwriter.println(
           "<td class='texttitulotabla' align='center'>No hay registros por desplegar</td>");
       printwriter.println("<tr>");
       printwriter.println("</table>");
     }
     printwriter.println("</body>");
     printwriter.println("</html>");
   } else {
     AFunc.reindex(httpservletrequest, printwriter, 1, "SAD", 6);
   }
 }
示例#20
0
  public synchronized void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    HttpSession dbSession = request.getSession();
    JspFactory _jspxFactory = JspFactory.getDefaultFactory();
    PageContext pageContext =
        _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
    ServletContext dbApplication = dbSession.getServletContext();

    ServletContext application;
    HttpSession session = request.getSession();
    nseer_db_backup1 finance_db = new nseer_db_backup1(dbApplication);

    try {

      if (finance_db.conn((String) dbSession.getAttribute("unit_db_name"))) {
        String finance_cheque_id = request.getParameter("finance_cheque_id");
        String sql = "delete from finance_bill where id='" + finance_cheque_id + "'";
        finance_db.executeUpdate(sql);
        finance_db.commit();
        finance_db.close();

      } else {
        response.sendRedirect("error_conn.htm");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
示例#21
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#22
0
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    if (pathInfo.equals("/")) {
      HttpSession session = req.getSession();
      if (session == null) {
        resp.setStatus(401);
        return;
      }
      String username = (String) session.getAttribute("username");
      if (username == null) {
        resp.setStatus(401);
        return;
      }

      Map userMap = loadUserSettingsMap(username);
      if (userMap == null) {
        resp.setStatus(401);
        return;
      }
      Enumeration parameterNames = req.getParameterNames();
      while (parameterNames.hasMoreElements()) {
        String parameterName = (String) parameterNames.nextElement();
        userMap.put(parameterName, req.getParameter(parameterName));
      }
      saveUserSettingsMap(username, userMap);
      return;
    }

    super.doPost(req, resp);
  }
示例#23
0
  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      userMap.clear();
    }
    String key = pathInfo.substring(1);
    userMap.remove(key);
    saveUserSettingsMap(username, userMap);
    return;
  }
示例#24
0
  private void rotateTokens(HttpServletRequest request) {
    HttpSession session = request.getSession(true);

    /** rotate master token * */
    String tokenFromSession = null;

    try {
      tokenFromSession = RandomGenerator.generateRandomId(getPrng(), getTokenLength());
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
    }

    session.setAttribute(getSessionKey(), tokenFromSession);

    /** rotate page token * */
    if (isTokenPerPageEnabled()) {
      @SuppressWarnings("unchecked")
      Map<String, String> pageTokens =
          (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

      try {
        pageTokens.put(
            request.getRequestURI(), RandomGenerator.generateRandomId(getPrng(), getTokenLength()));
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
      }
    }
  }
示例#25
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      resp.setContentType("application/json; charset=UTF-8");
      resp.getWriter().write(JSONUtil.write(userMap));
      return;
    }

    String key = pathInfo.substring(1);
    String value = (String) userMap.get(key);

    Map jsonObject = new HashMap();
    jsonObject.put(key, value);
    resp.setContentType("application/json; charset=UTF-8");
    resp.getWriter().write(JSONUtil.write(jsonObject));
  }
示例#26
0
  public void updateTokens(HttpServletRequest request) {
    /** cannot create sessions if response already committed * */
    HttpSession session = request.getSession(false);

    if (session != null) {
      /** create master token if it does not exist * */
      updateToken(session);

      /** create page specific token * */
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        /** first time initialization * */
        if (pageTokens == null) {
          pageTokens = new HashMap<String, String>();
          session.setAttribute(CsrfGuard.PAGE_TOKENS_KEY, pageTokens);
        }

        /** create token if it does not exist * */
        if (isProtectedPageAndMethod(request)) {
          createPageToken(pageTokens, request.getRequestURI());
        }
      }
    }
  }
示例#27
0
  public String getTokenValue(HttpServletRequest request, String uri) {
    String tokenValue = null;
    HttpSession session = request.getSession(false);

    if (session != null) {
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        if (pageTokens != null) {
          if (isTokenPerPagePrecreate()) {
            createPageToken(pageTokens, uri);
          }
          tokenValue = pageTokens.get(uri);
        }
      }

      if (tokenValue == null) {
        tokenValue = (String) session.getAttribute(getSessionKey());
      }
    }

    return tokenValue;
  }
示例#28
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Enumeration values = req.getParameterNames();
    String name = "";
    String value = "";
    String id = "";
    while (values.hasMoreElements()) {
      name = ((String) values.nextElement()).trim();
      value = req.getParameter(name).trim();
      if (name.equals("id")) id = value;
    }
    if (url.equals("")) {
      url = getServletContext().getInitParameter("url");
      cas_url = getServletContext().getInitParameter("cas_url");
    }
    HttpSession session = null;
    session = req.getSession(false);
    if (session != null) {
      session.invalidate();
    }
    res.sendRedirect(cas_url);
    return;
  }
示例#29
0
  /**
   * Get a populated User object from the request passed in.
   *
   * @param The request object to check for the user
   * @return The user object, or null if no user object was found
   */
  public static User getUser(HttpServletRequest request) {
    HttpSession session = request.getSession();
    if (session == null) {
      return null;
    }

    return (User) (session.getAttribute("user"));
  }
示例#30
0
 public void sessionDestroyed(HttpSessionEvent evt) {
   // Note: Session Fixation Protection (such as Spring Security)
   // might invalidate HTTP session and restore with a new one.
   // Thus, we use an attribute to denote this case and avoid the callback
   final HttpSession hsess = evt.getSession();
   if (hsess.getAttribute(Attributes.RENEW_NATIVE_SESSION) == null)
     WebManager.sessionDestroyed(hsess);
 }