Java Code Examples for javax.servlet.http.HttpServletRequest#getSession()

The following examples show how to use javax.servlet.http.HttpServletRequest#getSession() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityTokenService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getToken( HttpServletRequest request, String strAction )
{
    String strToken = generateNewKey( );
    HttpSession session = request.getSession( true );

    if ( session.getAttribute( PARAMETER_SESSION_TOKENS ) == null )
    {
        session.setAttribute( PARAMETER_SESSION_TOKENS, new HashMap<String, HashSet<String>>( ) );
    }

    Map<String, HashSet<String>> hashTokens = (Map<String, HashSet<String>>) session.getAttribute( PARAMETER_SESSION_TOKENS );

    if ( !hashTokens.containsKey( strAction ) )
    {
        hashTokens.put( strAction, new HashSet<>( ) );
    }

    hashTokens.get( strAction ).add( strToken );

    return strToken;
}
 
Example 2
Source File: DiscussionController.java    From voj with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 处理用户编辑讨论回复的请求.
 * @param discussionReplyId - 讨论回复的唯一标识符
 * @param replyContent - 讨论回复的内容
 * @param csrfToken - 用于防止CSRF攻击的Token
 * @param request - HttpServletRequest对象
 * @return 包含讨论回复编辑结果的JSON对象
 */
@RequestMapping(value="/{threadId}/editDiscussionReply.action", method=RequestMethod.POST)
public @ResponseBody Map<String, Boolean> editDiscussionReplyAction(
		@PathVariable("threadId") long discussionThreadId,
		@RequestParam(value="discussionReplyId") long discussionReplyId,
		@RequestParam(value="replyContent") String replyContent,
		@RequestParam(value="csrfToken") String csrfToken,
		HttpServletRequest request) {
	HttpSession session = request.getSession();
	String ipAddress = HttpRequestParser.getRemoteAddr(request);
	User currentUser = HttpSessionParser.getCurrentUser(session);
	boolean isCsrfTokenValid = CsrfProtector.isCsrfTokenValid(csrfToken, session);

	Map<String, Boolean> result = discussionService.editDiscussionReply(
			discussionReplyId, currentUser, replyContent, isCsrfTokenValid);
	if ( result.get("isSuccessful") ) {
		LOGGER.info(String.format("User: {%s} edited discussion reply #%d at %s",
				new Object[] {currentUser, discussionReplyId, ipAddress}));
	}
	return result;
}
 
Example 3
Source File: CSRFUtils.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public static String getCSRFToken(HttpServletRequest request, boolean create) {
    if (request != null && request.getSession() != null) {
        // Return an existing token first
        String savedToken = (String)request.getSession().getAttribute(CSRF_TOKEN);
        if (savedToken != null) {
            return savedToken;
        }

        // If no existing token then create a new one, save it, and return it
        if (create) {
            String token = StringUtils.toHexString(CryptoUtils.generateSecureRandomBytes(32));
            request.getSession().setAttribute(CSRF_TOKEN, token);
            return token;
        }
    }

    return null;
}
 
Example 4
Source File: OpendapServlet.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void doClose(ReqState rs) throws Exception {
  HttpServletResponse response = rs.getResponse();
  HttpServletRequest request = rs.getRequest();
  String reqPath = rs.getDataSet();
  HttpSession session = request.getSession();
  session.removeAttribute(reqPath); // work done in the listener

  response.setHeader("XDODS-Server", getServerVersion()); // needed by client

  /*
   * if (path.endsWith(".close")) {
   * closeSession(request, response);
   * response.setContentLength(0);
   * return;
   * }
   * 
   * // so we need to worry about deleting sessions?
   * session.invalidate();
   */
}
 
Example 5
Source File: BaseController.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * 获取request、response、session
 */
@ModelAttribute
public void setRequest(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.session = request.getSession();
}
 
Example 6
Source File: CustomOAuth2AuthenticationDetails.java    From spring-microservice-boilerplate with MIT License 5 votes vote down vote up
/**
 * Records the access token value and remote address and will also set the session Id if a session
 * already exists (it won't create one).
 *
 * @param request that the authentication request was received from
 */
public CustomOAuth2AuthenticationDetails(HttpServletRequest request) {
  this.tokenValue = (String) request.getAttribute(ACCESS_TOKEN_VALUE);
  this.tokenType = (String) request.getAttribute(ACCESS_TOKEN_TYPE);
  this.remoteAddress = RemoteAddressUtils.getRealIp(request);

  HttpSession session = request.getSession(false);
  this.sessionId = (session != null) ? session.getId() : null;
  StringBuilder builder = new StringBuilder();
  if (remoteAddress != null) {
    builder.append("remoteAddress=").append(remoteAddress);
  }
  if (builder.length() > 1) {
    builder.append(", ");
  }
  if (sessionId != null) {
    builder.append("sessionId=<SESSION>");
    if (builder.length() > 1) {
      builder.append(", ");
    }
  }
  if (tokenType != null) {
    builder.append("tokenType=").append(this.tokenType);
  }
  if (tokenValue != null) {
    builder.append("tokenValue=<TOKEN>");
  }
  this.display = builder.toString();
}
 
Example 7
Source File: ValidateUserEventAction.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public boolean checkAccount(HttpServletRequest request) {
	HttpSession session = request.getSession();
	ProjectObject project = SessionManager.getProjectObject(request);
	IUserSession userSession = (IUserSession) session.getAttribute("UserSession");
	// 判斷使用者是否為被啟用狀態
	AccountObject account = userSession.getAccount();
	if (!account.getEnable()) {
		return false;
	}
	ScrumRole sr = SessionManager.getScrumRole(request, project, account);

	if (sr == null) {
		return false;
	}

	// 判斷使用者是否為 guest 使用者
	if (sr.isGuest()) {
		return false;
	}

	// 判斷使用者是否為 admin 使用者
	if (sr.isAdmin()) {
		return true;
	}

	/*			// 判斷使用者是否為存在於資料庫的使用者
				if ( ! existUser(acc.getID())) {
					return false;
				}*/

	return true;
}
 
Example 8
Source File: OAuth2AuthenticationSuccessHandler.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
private void clearAuthenticationAttributes(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    if (session == null) {
        return;
    }
    session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
 
Example 9
Source File: SessionComponentImpl.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> getAttribute(String key) {
    try {
        final HttpServletRequest request = HttpContext.get(HttpServletRequest.class);
        final HttpSession session = request.getSession();
        final Map<String, Object> map = HttpStatus.OK.to().beanToMap();
        final Object value = session.getAttribute(key);
        map.put(key, value == null ? "" : value);
        return map;
    } catch(final Throwable e) {
        return HttpStatus.INTERNAL_SERVER_ERROR.to().beanToMap();
    }
}
 
Example 10
Source File: LoginFilter.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void redirectToLogin(HttpServletRequest httpReq, ServletResponse response) throws IOException {
    HttpSession session = httpReq.getSession();
    HttpServletResponse httpResp = (HttpServletResponse) response;

    session.setAttribute("loginFrom", httpReq.getRequestURI());
    String context = httpReq.getContextPath();
    httpResp.sendRedirect(context+ Paths.LOGIN);
}
 
Example 11
Source File: LoginController.java    From sylph with Apache License 2.0 5 votes vote down vote up
@Path("/logout")
@GET
@Produces({MediaType.APPLICATION_JSON})
public boolean doLogout(@Context HttpServletRequest req)
{
    HttpSession session = req.getSession(); //获取当前session
    if (session != null) {
        User user = (User) session.getAttribute("user"); //从当前session中获取用户信息
        session.invalidate(); //关闭session
    }
    return true;
}
 
Example 12
Source File: Prj3100Controller.java    From oslits with GNU General Public License v3.0 5 votes vote down vote up
/**
	 * Prj3100 메뉴정보 수정(단건) AJAX
	 * 메뉴정보 수정 처리
	 * @param 
	 * @return 
	 * @exception Exception
	 */
	@RequestMapping(value="/prj/prj3000/prj3100/updatePrj3100MenuInfoAjax.do")
    public ModelAndView updatePrj3100MenuInfoAjax(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {
    	
    	try{
        	
    		// request 파라미터를 map으로 변환
        	Map<String, String> paramMap = RequestConvertor.requestParamToMap(request, true);
        	
        	HttpSession ss = request.getSession();
        	paramMap.put("prjId", (String)ss.getAttribute("selPrjId"));
     	
     	
        	// 메뉴 수정
        	prj3100Service.updatePrj3100MenuInfo(paramMap);
        	
        	//등록 성공 메시지 세팅
        	model.addAttribute("message", egovMessageSource.getMessage("success.common.update"));
        	
        	return new ModelAndView("jsonView");
    	}
    	catch(Exception ex){
    		Log.error("updateAdm1000MenuInfoAjax()", ex);

    		//수정 실패 메시지 세팅 및 저장 성공여부 세팅
    		model.addAttribute("saveYN", "N");
    		model.addAttribute("message", egovMessageSource.getMessage("fail.common.update"));
    		return new ModelAndView("jsonView");
    	}
}
 
Example 13
Source File: BackTracker.java    From unitime with Apache License 2.0 5 votes vote down vote up
public static void markForBack(HttpServletRequest request, String uri, String title, boolean back, boolean clear) {
	synchronized (request.getSession()) {
		Vector backList = getBackList(request.getSession());
		if (clear) backList.clear();
		if (back) {
			if (uri==null && request.getAttribute("javax.servlet.forward.request_uri")==null) return;
			Object titleObj = (title==null?request.getAttribute("title"):title);
			String requestURI = (String)request.getAttribute("javax.servlet.forward.request_uri");
			String queryString = (String)request.getAttribute("javax.servlet.forward.query_string");
			if (queryString!=null && queryString.length()>0)
				requestURI += "?"+queryString;
			if (uri!=null)
				requestURI = uri;
			if (!backList.isEmpty()) {
				int found = -1;
				for (int idx = 0; idx<backList.size(); idx++) {
					String[] lastBack = (String[])backList.elementAt(idx);
					if (lastBack[0].equals(requestURI)) {
						found = idx; break;
					}
				}
				while (found>=0 && backList.size()>found)
					backList.removeElementAt(backList.size()-1);
			}
			backList.addElement(new String[]{requestURI,(titleObj==null?null:titleObj.toString())});
			//System.out.println("ADD BACK:"+requestURI+" ("+titleObj+")");
		}
	}
}
 
Example 14
Source File: MyServlet.java    From journaldev with MIT License 5 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext ctx = request.getServletContext();
		ctx.setAttribute("User", "Pankaj");
		String user = (String) ctx.getAttribute("User");
		ctx.removeAttribute("User");
		
		HttpSession session = request.getSession();
		session.invalidate();
		
		PrintWriter out = response.getWriter();
		out.write("Hi "+user);
}
 
Example 15
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // get client
    //final String clientName = request.getParameter(this.clients.getClientNameParameter());
    final String clientName = request.getParameter("state");
    //logger.debug("clientName : {}", clientName);
    logger.info("clientName : {}", clientName);

    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client =
                (BaseClient<Credentials, CommonProfile>) this.clients
                .findClient(clientName);
        logger.info("client : {}", client);

        // Only supported protocols
        final Mechanism mechanism = client.getMechanism();
        logger.info("mechanism == " + mechanism.name());
        if (!SUPPORTED_PROTOCOLS.contains(mechanism)) {
            throw new TechnicalException("Only CAS, OAuth, OpenID and SAML protocols are supported: " + client);
        }

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            logger.info("credentials : {}", credentials);
        } catch (final RequiresHttpAction e) {
            logger.info("requires http action : {}", e);
            response.flushBuffer();
            ExternalContext externalContext = ExternalContextHolder.getExternalContext();
            externalContext.recordResponseComplete();
            return new Event(this, "stop");
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(SERVICE);
        context.getFlowScope().put(SERVICE, service);
        logger.info("retrieve service: {}", service);
        if (service != null) {
            request.setAttribute(SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, THEME);
        restoreRequestAttribute(request, session, LOCALE);
        restoreRequestAttribute(request, session, METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            logger.info("credentials is not null : {}", credentials);
            WebUtils.putTicketGrantingTicketInRequestScope(context,
                    this.centralAuthenticationService.createTicketGrantingTicket(new ClientCredential(credentials)));
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    return error();
}
 
Example 16
Source File: SessionServlet.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private String getCounterWrapper(HttpServletRequest req) {
    HttpSession session = req.getSession();
    return String.valueOf(session.getAttribute("counterWrapper"));
}
 
Example 17
Source File: AccountController.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@RequestMapping(value="/list.do")
  public String accountList(@ModelAttribute("accountVO") AccountVO accountVO,
  		                   HttpServletRequest request,
  		                   Locale locale,
  		                   ModelMap model)
          throws Exception {

HttpSession session = request.getSession(false);
if(session != null){
	//페이지 권한 확인
	GroupAuthorization requestAuth = (GroupAuthorization) session.getAttribute("requestAuth");
	if(!requestAuth.getAuthorizationDBRead().equals("1")){
		model.addAttribute("authMessage", "사용자관리 메뉴는 읽기 권한이 없습니다.");
		return "forward:" + HeritProperties.getProperty("Globals.MainPage");
	}
}


      //조회 페이지의 검색키워드 보안 취약점 보완
      String currPage = SecurityModule.VulnerabilityChek(StringUtil.nvl(request.getParameter("currPage"), "1"), 1, "common", "xss|sqlinjection");
      int nPage = Integer.parseInt(currPage);
      if (nPage < 1) {
          nPage = 1;
      }


      //조회 페이지의 검색키워드 보안 취약점 보완
      accountVO.setSearchVal(SecurityModule.VulnerabilityChek(StringUtil.nvl(accountVO.getSearchVal()), 1, "common", "xss|sqlinjection"));
      PagingUtil resultPagingUtil = accountService.accountPagingList(nPage, accountVO);
      List mngAccountGroupIdList = accountService.getMngAccountGroupIdList();

/**
 * 데이터 셋팅
 */
model.addAttribute("accountVO", accountVO);
model.addAttribute("currPage", currPage);
model.addAttribute("mngAccountGroupIdList", mngAccountGroupIdList);
model.addAttribute("resultPagingUtil", resultPagingUtil);

  	return "/herit/business/admin/accountList";
  }
 
Example 18
Source File: VerifyServlet.java    From blog-sample with Apache License 2.0 4 votes vote down vote up
/**
 * @param request
 * @param response
 * @throws ServletException
 * @throws java.io.IOException
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
    // 定义图像buffer
    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gd = buffImg.createGraphics();
    // 创建一个随机数生成器类
    Random random = new Random();
    // 将图像填充为白色
    gd.setColor(Color.LIGHT_GRAY);
    gd.fillRect(0, 0, width, height);
    // 创建字体,字体的大小应该根据图片的高度来定。
    Font font = new Font("Times New Roman", Font.PLAIN, fontHeight);
    // 设置字体。
    gd.setFont(font);
    // 画边框。
    gd.setColor(Color.BLACK);
    gd.drawRect(0, 0, width - 1, height - 1);
    // 随机产生16条干扰线,使图象中的认证码不易被其它程序探测到。
    gd.setColor(Color.gray);
    for (int i = 0; i < interLine; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        gd.drawLine(x, y, x + xl, y + yl);
    }
    // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
    StringBuffer randomCode = new StringBuffer();
    int red = 0, green = 0, blue = 0;
    // 随机产生codeCount数字的验证码。
    for (int i = 0; i < codeCount; i++) {
        // 得到随机产生的验证码数字。
        String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
        // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
        red = random.nextInt(255);
        green = random.nextInt(255);
        blue = random.nextInt(255);
        // 用随机产生的颜色将验证码绘制到图像中。
        gd.setColor(new Color(red, green, blue));
        gd.drawString(strRand, (i + 1) * codeX, codeY);
        // 将产生的四个随机数组合在一起。
        randomCode.append(strRand);
    }
    // 将四位数字的验证码保存到Session中。
    HttpSession session = request.getSession();
    session.setAttribute("validateCode", randomCode.toString());
    // 禁止图像缓存。
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    response.setContentType("image/jpeg");
    // 将图像输出到Servlet输出流中。
    ServletOutputStream sos = response.getOutputStream();
    ImageIO.write(buffImg, "jpeg", sos);
    sos.close();
}
 
Example 19
Source File: Stm4000Controller.java    From oslits with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Stm4000 프로젝트를 수정한다
 * @param
 * @return update row, 프로젝트ID
 * @exception Exception
 */
   @SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value="/stm/stm4000/stm4000/updateStm4000PrjInfoAjax.do")
   public ModelAndView updateStm4000PrjInfoAjax(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {
   	try{
   		// request 파라미터를 map으로 변환
       	Map<String, String> paramMap = RequestConvertor.requestParamToMap(request, true);
       	
       	// 프로젝트 약어
   		String prjAcrmStr = paramMap.get("prjAcrm");
   		
   		// 프로젝트 약어가 있을 경우
   		if(prjAcrmStr != null){
   			// Map에 프로젝트 약어 추가
       		paramMap.put("prjAcrm", prjAcrmStr.toUpperCase());
   		}
       	
       	// 프로젝트 수정
       	int updateCnt = prj1000Service.updatePrj1000Ajax(paramMap);
       	
       	// 프로젝트 ID와 프로젝트 수정 count 값을 세팅
       	model.put("prjId", paramMap.get("prjId"));
       	model.put("updateCnt", updateCnt);
       	// 수정 성공여부 및 수정 성공 메시지 세팅
       	model.addAttribute("errorYn", "N");
       	model.addAttribute("message", egovMessageSource.getMessage("success.common.update"));
       	
       	//세션 정보 가져오기
		HttpSession ss = request.getSession();
		// LoginVO를 가져온다
		LoginVO loginVO = (LoginVO) ss.getAttribute("loginVO");
		
		// 사용자 ID를 가져온다.
		String usrId = (String)loginVO.getUsrId();
		paramMap.put("usrId", usrId);
		
		// 세션 재세팅을 위한 프로젝트 목록 불러올 때 프로젝트 그룹값 Map에서 제거한다.
		// 그렇지 않으면 단위 프로젝트만 조회되어 세션에 세팅된다.
		paramMap.remove("prjGrpCd");
		
       	// 사용자 권한있는 프로젝트 목록 조회
		List<Map> prjList = (List)prj1000Service.selectPrj1000View(paramMap);

   		// 세션에 있는 기존 프로젝트 목록 제거
   		ss.removeAttribute("prjList");
   		
   		// 조회한 권한있는 프로젝트 목록을 세션에 재세팅
   		ss.setAttribute("prjList", prjList);
   		
       	return new ModelAndView("jsonView", model);
   	}
   	catch(Exception ex){
   		Log.error("updateStm4000PrjInfoAjax()", ex);
         	// 수정 실패여부 및 수정 실패 메시지 세팅
       	model.addAttribute("errorYn", "Y");
   		model.addAttribute("message", egovMessageSource.getMessage("fail.common.update"));
   		return new ModelAndView("jsonView");
   	}
   }
 
Example 20
Source File: OIDCUtils.java    From shibboleth-oidc with Apache License 2.0 3 votes vote down vote up
/**
 * Put session attribute.
 *
 * @param request   the request
 * @param parameter the parameter
 * @param value     the value
 */
public static void putSessionAttribute(final HttpServletRequest request,
                                       final String parameter,
                                       final Object value) {
    final HttpSession session = request.getSession();
    session.setAttribute(parameter, value);
}