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

The following examples show how to use javax.servlet.http.HttpServletRequest#getRemoteUser() . These examples are extracted from open source projects. 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
private String createPlayerIfNecessary(HttpServletRequest request, boolean jukebox) {
    String username = request.getRemoteUser();
    String clientId = request.getParameter("c");
    if (jukebox) {
        clientId += "-jukebox";
    }

    List<Player> players = playerService.getPlayersForUserAndClientId(username, clientId);

    // If not found, create it.
    if (players.isEmpty()) {
        Player player = new Player();
        player.setIpAddress(request.getRemoteAddr());
        player.setUsername(username);
        player.setClientId(clientId);
        player.setName(clientId);
        player.setTechnology(jukebox ? PlayerTechnology.JUKEBOX : PlayerTechnology.EXTERNAL_WITH_PLAYLIST);
        playerService.createPlayer(player);
        players = playerService.getPlayersForUserAndClientId(username, clientId);
    }

    // Return the player ID.
    return !players.isEmpty() ? String.valueOf(players.get(0).getId()) : null;
}
 
Example 2
@Override
protected synchronized void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	traceRequest(req);
	String userName = req.getRemoteUser();
	if (userName == null) {
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request: authenticated user is null", null));
		return;
	}
	if (getPathInfo(req).segmentCount() == 1) {
		SiteInfo site = getExistingSiteConfig(req, resp, userName);
		if (siteConfigurationResourceHandler.handleRequest(req, resp, site)) {
			return;
		}
	} else {
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request", null));
	}
	super.doDelete(req, resp);
}
 
Example 3
Source Project: apiman   File: AuthTokenGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see io.apiman.manager.ui.server.auth.ITokenGenerator#generateToken(javax.servlet.http.HttpServletRequest)
 */
@Override
public BearerTokenCredentialsBean generateToken(HttpServletRequest request) {
    BearerTokenCredentialsBean bean = new BearerTokenCredentialsBean();
    
    String principal = request.getRemoteUser();
    // TODO create platform specific subclasses of this to get the roles properly
    Set<String> roles = new HashSet<>();
    roles.add("apiuser"); //$NON-NLS-1$
    if (request.isUserInRole("apiadmin")) { //$NON-NLS-1$
        roles.add("apiadmin"); //$NON-NLS-1$
    }
    String token = AuthTokenUtil.produceToken(principal, roles, TEN_MINUTES);
    bean.setToken(token);
    bean.setRefreshPeriod(NINE_MINUTES);
    return bean;
}
 
Example 4
Source Project: hadoop   File: RMWebServices.java    License: Apache License 2.0 6 votes vote down vote up
private UserGroupInformation getCallerUserGroupInformation(
    HttpServletRequest hsr, boolean usePrincipal) {

  String remoteUser = hsr.getRemoteUser();
  if (usePrincipal) {
    Principal princ = hsr.getUserPrincipal();
    remoteUser = princ == null ? null : princ.getName();
  }

  UserGroupInformation callerUGI = null;
  if (remoteUser != null) {
    callerUGI = UserGroupInformation.createRemoteUser(remoteUser);
  }

  return callerUGI;
}
 
Example 5
@Override
protected synchronized void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	traceRequest(req);
	String userName = req.getRemoteUser();
	if (userName == null) {
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request: authenticated user is null", null));
		return;
	}
	IPath pathInfo = getPathInfo(req);
	if (pathInfo.segmentCount() == 0) {
		doGetAllSiteConfigurations(req, resp, userName);
		return;
	} else if (pathInfo.segmentCount() == 1) {
		SiteInfo site = getExistingSiteConfig(req, resp, userName);
		if (siteConfigurationResourceHandler.handleRequest(req, resp, site)) {
			return;
		}
	} else {
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request", null));
		return;
	}
	super.doGet(req, resp);
}
 
Example 6
Source Project: hadoop   File: WebServices.java    License: Apache License 2.0 5 votes vote down vote up
protected static UserGroupInformation getUser(HttpServletRequest req) {
  String remoteUser = req.getRemoteUser();
  UserGroupInformation callerUGI = null;
  if (remoteUser != null) {
    callerUGI = UserGroupInformation.createRemoteUser(remoteUser);
  }
  return callerUGI;
}
 
Example 7
Source Project: hadoop   File: AMWebServices.java    License: Apache License 2.0 5 votes vote down vote up
Boolean hasAccess(Job job, HttpServletRequest request) {
  String remoteUser = request.getRemoteUser();
  UserGroupInformation callerUGI = null;
  if (remoteUser != null) {
    callerUGI = UserGroupInformation.createRemoteUser(remoteUser);
  }
  if (callerUGI != null && !job.checkAccess(callerUGI, JobACL.VIEW_JOB)) {
    return false;
  }
  return true;
}
 
Example 8
public static final String getUserId(HttpServletRequest req) {
	if (req.getRemoteUser() != null) {
		return req.getRemoteUser();
	} else {
		return req.getSession(true).getId();
	}
}
 
Example 9
public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1, Object handler) throws Exception {

		if(request.getRequestURI().endsWith("products/add") && request.getMethod().equals("POST")){
			user = request.getRemoteUser();
			productId = request.getParameterValues("productId")[0];
		}
		return true;
	}
 
Example 10
Source Project: qpid-broker-j   File: SaslServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request,
                     HttpServletResponse response,
                     final ConfiguredObject<?> managedObject) throws ServletException, IOException
{
    getRandom(request);

    AuthenticationProvider<?> authenticationProvider = getAuthenticationProvider(request);
    List<String> mechanismsList = authenticationProvider.getAvailableMechanisms(request.isSecure());
    String[] mechanisms = mechanismsList.toArray(new String[mechanismsList.size()]);
    Map<String, Object> outputObject = new LinkedHashMap<String, Object>();

    final Subject subject = Subject.getSubject(AccessController.getContext());
    final Principal principal = AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subject);
    if(principal != null)
    {
        outputObject.put("user", principal.getName());
    }
    else if (request.getRemoteUser() != null)
    {
        outputObject.put("user", request.getRemoteUser());
    }

    outputObject.put("mechanisms", (Object) mechanisms);

    sendJsonResponse(outputObject, request, response);

}
 
Example 11
/**
 * Sets the default scopes to the location of each project.
 * @param req The request from the servlet.
 * @param res The response to the servlet.
 * @throws SearchException Thrown if there is an error reading a file.
 */
private void setDefaultScopes(HttpServletRequest req, HttpServletResponse resp, SearchOptions options) throws SearchException {
	String login = req.getRemoteUser();
	try {
		UserInfo userInfo = OrionConfiguration.getMetaStore().readUserByProperty(UserConstants.USER_NAME, login, false, false);
		List<String> workspaceIds = userInfo.getWorkspaceIds();
		for (String workspaceId : workspaceIds) {
			WorkspaceInfo workspaceInfo = OrionConfiguration.getMetaStore().readWorkspace(workspaceId);
			options.setDefaultLocation("/file/" + workspaceId);
			addAllProjectsToScope(workspaceInfo, options);
		}
	} catch (CoreException e) {
		throw (new SearchException(e));
	}
}
 
Example 12
/**
    * @param mapping
    *            The ActionMapping used to select this instance
    * @param actionForm
    *            The optional ActionForm bean for this request (if any)
    * @param request
    *            The HTTP request we are processing
    * @param response
    *            The HTTP response we are creating
    *
    */
   @RequestMapping(path = "/passwordChanged", method = RequestMethod.POST)
   public String execute(@ModelAttribute("PasswordChangeActionForm") PasswordChangeActionForm passwordChangeForm,
    HttpServletRequest request) throws Exception {

MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();

if (errorMap.isEmpty()) {
    try {

	String loggedInUser = request.getRemoteUser();
	String login = passwordChangeForm.getLogin();
	String oldPassword = passwordChangeForm.getOldPassword();
	String password = passwordChangeForm.getPassword();
	String passwordConfirm = passwordChangeForm.getPasswordConfirm();

	if ((loggedInUser == null) || !loggedInUser.equals(login)) {
	    errorMap.add("GLOBAL", messageService.getMessage("error.authorisation"));
	    
	} else {
	    User user = userManagementService.getUserByLogin(login);
	    String passwordHash = user.getPassword().length() == HashUtil.SHA1_HEX_LENGTH
		    ? HashUtil.sha1(oldPassword)
		    : HashUtil.sha256(oldPassword, user.getSalt());

	    if (!user.getPassword().equals(passwordHash)) {
		errorMap.add("oldPassword", messageService.getMessage("error.oldpassword.mismatch"));
		PasswordChangeController.log.debug("old pass wrong");
	    }
	    if (!password.equals(passwordConfirm)) {
		errorMap.add("password", messageService.getMessage("error.newpassword.mismatch"));
		PasswordChangeController.log.debug("new pass wrong");
	    }
	    if ((password == null) || (password.length() == 0)) {
		errorMap.add("password", messageService.getMessage("error.password.empty"));
		PasswordChangeController.log.debug("new password cannot be empty");
	    }
	    if (!ValidationUtil.isPasswordValueValid(password, passwordConfirm)) {
		errorMap.add("password", messageService.getMessage("label.password.restrictions"));
		PasswordChangeController.log.debug("Password must follow the restrictions");
	    }

	    if (errorMap.isEmpty()) {
		String salt = HashUtil.salt();
		user.setSalt(salt);
		user.setPassword(HashUtil.sha256(password, salt));
		user.setChangePassword(false);
		userManagementService.saveUser(user);

		// make 'password changed' audit log entry
		String[] args = new String[1];
		args[0] = user.getLogin() + " (" + user.getUserId() + ")";
		String message = messageService.getMessage("audit.user.password.change", args);
		logEventService.logEvent(LogEvent.TYPE_PASSWORD_CHANGE, user.getUserId(), user.getUserId(), null, null,
			message);
	    }
	}

    } catch (Exception e) {
	PasswordChangeController.log.error("Exception occured ", e);
	errorMap.add("GLOBAL", messageService.getMessage(e.getMessage()));
    }

} // end if no errors

// -- Report any errors
if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return "passwordChangeContent";
}
request.setAttribute("redirectURL", passwordChangeForm.getRedirectURL());
return "/passwordChangeOkContent";
   }
 
Example 13
/**
 * Read user id.
 * 
 * @param session
 *            HttpSession
 * 
 * @return String
 */
public String readUserIdentifier(HttpServletRequest request) {
	String user;

	logger.debug("IN");

	Assert.assertNotNull(request, "Input parameter [request] cannot be null");

	user = null;

	try {

		user = request.getParameter(USER_IDENTIFIER_REQUEST_HEADER_NAME);
		logger.debug("Request parameter [" + USER_IDENTIFIER_REQUEST_HEADER_NAME + "] is equal to [" + user + "]");

		user = request.getHeader(USER_IDENTIFIER_REQUEST_HEADER_NAME);
		logger.debug("Request header [" + USER_IDENTIFIER_REQUEST_HEADER_NAME + "] is equal to [" + user + "]");

		user = request.getRemoteUser();
		logger.debug("Remote user is equal to [" + user + "]");

		user = (String) request.getAttribute(USER_IDENTIFIER_REQUEST_HEADER_NAME);
		logger.debug("Request attribute [" + USER_IDENTIFIER_REQUEST_HEADER_NAME + "] is equal to [" + user + "]");

		if (user != null) {

			if (user.lastIndexOf('@') != -1) {
				user = user.substring(0, user.lastIndexOf('@'));
			}

			user = user.toUpperCase();
			logger.debug("Incoming request come from the autenthicated user [" + user + "]");
		} else {
			// if "Proxy-Remote-User" is null dump all header in the request just for debug purpose
			logger.debug("Impossible to read  header [" + USER_IDENTIFIER_REQUEST_HEADER_NAME + "] from request");
			Enumeration headerNames = request.getHeaderNames();
			while (headerNames.hasMoreElements()) {
				String headerName = (String) headerNames.nextElement();
				logger.debug("Request header [" + headerName + "] is equal to [" + request.getHeader(headerName) + "]");
			}

			logger.debug("Incoming request come from a user not yet authenticated");
		}

	} catch (Throwable t) {
		// fail fast
		throw new RuntimeException("An unpredicted error occurred while reading user identifier", t);
	} finally {
		logger.debug("OUT");
	}

	return user;
}
 
Example 14
Source Project: incubator-atlas   File: Servlets.java    License: Apache License 2.0 4 votes vote down vote up
public static String getUserName(HttpServletRequest httpServletRequest) throws IOException {
    return httpServletRequest.getRemoteUser();
}
 
Example 15
/**
 * Handles the special Webdav methods
 */
protected void doDispatch(SakaidavServletInfo info, HttpServletRequest req, HttpServletResponse resp) throws ServletException,
		IOException
{

	String method = req.getMethod();

	if (log.isDebugEnabled())
	{
		String path = getRelativePath(req);
		log.debug("SAKAIDAV doDispatch [" + method + "] " + path);
	}

	String remoteUser = req.getRemoteUser();
	if (log.isDebugEnabled()) log.debug("SAKAIDAV remoteuser = " + remoteUser);
	if (remoteUser == null)
	{
		if (log.isDebugEnabled()) log.debug("SAKAIDAV Requires Authorization");
		resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
		return;
	}

	if (method.equals(METHOD_PROPFIND))
	{
		doPropfind(req, resp);
	}
	else if (method.equals(METHOD_PROPPATCH))
	{
		doProppatch(req, resp);
	}
	else if (method.equals(METHOD_MKCOL))
	{
		doMkcol(req, resp);
	}
	else if (method.equals(METHOD_COPY))
	{
		doCopy(req, resp);
	}
	else if (method.equals(METHOD_MOVE))
	{
		doMove(req, resp);
	}
	else if (method.equals(METHOD_LOCK))
	{
		doLock(req, resp);
	}
	else if (method.equals(METHOD_UNLOCK))
	{
		doUnlock(req, resp);
	}
	else if (method.equals(METHOD_GET))
	{
		doGet(req, resp);
	}
	else if (method.equals(METHOD_PUT))
	{
		doPut(req, resp);
	}
	else if (method.equals(METHOD_POST))
	{
		doPost(req, resp);
	}
	else if (method.equals(METHOD_HEAD))
	{
		doHead(req, resp);
	}
	else if (method.equals(METHOD_OPTIONS))
	{
		doOptions(req, resp);
	}
	else if (method.equals(METHOD_DELETE))
	{
		doDelete(req, resp);
	}
	else
	{
		log.warn("SAKAIDAV:Request not supported");
		resp.sendError(SakaidavStatus.SC_NOT_IMPLEMENTED);
		// showRequestInfo(req);
	}

}
 
Example 16
Source Project: jqm   File: LogFilter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
    long t1 = System.nanoTime();
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    // Add username to log context if user is logged
    Principal p = req.getUserPrincipal();
    String username = p != null ? p.getName() : null;
    if (username != null && !username.trim().isEmpty())
    {
        MDC.put("username", username);
    }
    else
    {
        MDC.put("username", "anonymous");
    }
    String userOsName = req.getRemoteUser();
    if (userOsName != null)
    {
        MDC.put("identity", userOsName);
    }
    else
    {
        MDC.put("identity", "-");
    }

    // Session
    HttpSession s = req.getSession(false);
    if (s != null)
    {
        MDC.put("sessionid", s.getId());
    }
    else
    {
        MDC.put("sessionid", "-1");
    }

    // IP
    MDC.put("ip", req.getRemoteAddr());

    // Go on, and clean at the end.
    try
    {
        chain.doFilter(request, response);
    }
    finally
    {
        log.info("\"" + req.getMethod() + " " + req.getRequestURI() + " " + req.getProtocol() + "\" " + res.getStatus() + " - "
                + ((System.nanoTime() - t1) / 1000000));
        MDC.clear();
    }
}
 
Example 17
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    updateSessionManager(request);

    if (isMultipleInstancesAdmin(request) || request.isUserInRole(Config.DEFAULT_ADMIN_ROLE)) {
        try {

            if (action.equals("userCreate")) {
                userCreate(userId, request, response);
            } else if (action.equals("roleCreate")) {
                roleCreate(userId, request, response);
            } else if (action.equals("userEdit")) {
                userEdit(userId, request, response);
            } else if (action.equals("roleEdit")) {
                roleEdit(userId, request, response);
            } else if (action.equals("userDelete")) {
                userDelete(userId, request, response);
            } else if (action.equals("roleDelete")) {
                roleDelete(userId, request, response);
            }

            // Go to list
            if (action.startsWith("user")) {
                response.sendRedirect(request.getContextPath() + request.getServletPath() + "?action=userList");
            } else {
                response.sendRedirect(request.getContextPath() + request.getServletPath() + "?action=roleList");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            sendErrorRedirect(request, response, e);
        }
    } else {
        // Activity log
        UserActivity.log(request.getRemoteUser(), "ADMIN_ACCESS_DENIED", request.getRequestURI(), null,
                request.getQueryString());

        AccessDeniedException ade = new AccessDeniedException("You should not access this resource");
        sendErrorRedirect(request, response, ade);
    }
}
 
Example 18
Source Project: big-c   File: GetJournalEditServlet.java    License: Apache License 2.0 4 votes vote down vote up
protected boolean isValidRequestor(HttpServletRequest request, Configuration conf)
    throws IOException {
  String remotePrincipal = request.getUserPrincipal().getName();
  String remoteShortName = request.getRemoteUser();
  if (remotePrincipal == null) { // This really shouldn't happen...
    LOG.warn("Received null remoteUser while authorizing access to " +
        "GetJournalEditServlet");
    return false;
  }

  if (LOG.isDebugEnabled()) {
    LOG.debug("Validating request made by " + remotePrincipal +
        " / " + remoteShortName + ". This user is: " +
        UserGroupInformation.getLoginUser());
  }

  Set<String> validRequestors = new HashSet<String>();
  validRequestors.addAll(DFSUtil.getAllNnPrincipals(conf));
  try {
    validRequestors.add(
        SecurityUtil.getServerPrincipal(conf
            .get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KERBEROS_PRINCIPAL_KEY),
            SecondaryNameNode.getHttpAddress(conf).getHostName()));
  } catch (Exception e) {
    // Don't halt if SecondaryNameNode principal could not be added.
    LOG.debug("SecondaryNameNode principal could not be added", e);
    String msg = String.format(
      "SecondaryNameNode principal not considered, %s = %s, %s = %s",
      DFSConfigKeys.DFS_SECONDARY_NAMENODE_KERBEROS_PRINCIPAL_KEY,
      conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KERBEROS_PRINCIPAL_KEY),
      DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY,
      conf.get(DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY,
        DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_DEFAULT));
    LOG.warn(msg);
  }

  // Check the full principal name of all the configured valid requestors.
  for (String v : validRequestors) {
    if (LOG.isDebugEnabled())
      LOG.debug("isValidRequestor is comparing to valid requestor: " + v);
    if (v != null && v.equals(remotePrincipal)) {
      if (LOG.isDebugEnabled())
        LOG.debug("isValidRequestor is allowing: " + remotePrincipal);
      return true;
    }
  }

  // Additionally, we compare the short name of the requestor to this JN's
  // username, because we want to allow requests from other JNs during
  // recovery, but we can't enumerate the full list of JNs.
  if (remoteShortName.equals(
        UserGroupInformation.getLoginUser().getShortUserName())) {
    if (LOG.isDebugEnabled())
      LOG.debug("isValidRequestor is allowing other JN principal: " +
          remotePrincipal);
    return true;
  }

  if (LOG.isDebugEnabled())
    LOG.debug("isValidRequestor is rejecting: " + remotePrincipal);
  return false;
}
 
Example 19
/**
 * Handles the special Webdav methods
 */
protected void doDispatch(SakaidavServletInfo info, HttpServletRequest req, HttpServletResponse resp) throws ServletException,
		IOException
{

	String method = req.getMethod();

	if (log.isDebugEnabled())
	{
		String path = getRelativePath(req);
		log.debug("SAKAIDAV doDispatch [" + method + "] " + path);
	}

	String remoteUser = req.getRemoteUser();
	if (log.isDebugEnabled()) log.debug("SAKAIDAV remoteuser = " + remoteUser);
	if (remoteUser == null)
	{
		if (log.isDebugEnabled()) log.debug("SAKAIDAV Requires Authorization");
		resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
		return;
	}

	if (method.equals(METHOD_PROPFIND))
	{
		doPropfind(req, resp);
	}
	else if (method.equals(METHOD_PROPPATCH))
	{
		doProppatch(req, resp);
	}
	else if (method.equals(METHOD_MKCOL))
	{
		doMkcol(req, resp);
	}
	else if (method.equals(METHOD_COPY))
	{
		doCopy(req, resp);
	}
	else if (method.equals(METHOD_MOVE))
	{
		doMove(req, resp);
	}
	else if (method.equals(METHOD_LOCK))
	{
		doLock(req, resp);
	}
	else if (method.equals(METHOD_UNLOCK))
	{
		doUnlock(req, resp);
	}
	else if (method.equals(METHOD_GET))
	{
		doGet(req, resp);
	}
	else if (method.equals(METHOD_PUT))
	{
		doPut(req, resp);
	}
	else if (method.equals(METHOD_POST))
	{
		doPost(req, resp);
	}
	else if (method.equals(METHOD_HEAD))
	{
		doHead(req, resp);
	}
	else if (method.equals(METHOD_OPTIONS))
	{
		doOptions(req, resp);
	}
	else if (method.equals(METHOD_DELETE))
	{
		doDelete(req, resp);
	}
	else
	{
		log.warn("SAKAIDAV:Request not supported");
		resp.sendError(SakaidavStatus.SC_NOT_IMPLEMENTED);
		// showRequestInfo(req);
	}

}
 
Example 20
/**
 * Obtain and return the user name from the request headers.
 */
private String getUserId(HttpServletRequest req) {
	return req.getRemoteUser();
}