Validates that the user making the request is a privileged user.

@param   req  - Http Request

@throws  WebApplicationException  Throws exception if user is not a privileged user.
430324
protected void validatePrivilegedUser(HttpServletRequest req) {
        if (!getRemoteUser(req).isPrivileged()) {
            throw new WebApplicationException(Status.FORBIDDEN.getReasonPhrase(), Status.FORBIDDEN);
        }
    }
1208390
@Override
  protected void additionalAuthenticationChecks(UserDetails userDetails,
      UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    // default implementation authentications via servlet API (container managed)
    ServletRequestAttributes currentRequestAttributes =
        (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

    HttpServletRequest request = currentRequestAttributes.getRequest();
    String login = authentication.getName();
    String password = null;
    Object credentials = authentication.getCredentials();
    if (credentials != null) {
      password = credentials.toString();
    }
    try {
      request.login(login, password);
    } catch (ServletException e) {
      LOG.warn("Authentication failed: {}", e.toString());
      throw new BadCredentialsException("Authentication failed.", e);
    }
    authentication.setDetails(userDetails);
  }
1214554
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		if (requestURI.endsWith(OAUTH2_ACTION)) {
			String authCode = request.getParameter("code");
			if (!StringUtils.isBlank(authCode)) {
				String appid = SecurityUtils.getAppidFromAuthRequest(request);
				String redirectURI = SecurityUtils.getRedirectUrl(request);
				App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
				String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.OAUTH2_PREFIX);
				String entity = Utils.formatMessage(PAYLOAD,
						authCode, Utils.urlEncode(redirectURI),
						URLEncoder.encode(SecurityUtils.getSettingForApp(app, "security.oauth.scope", ""), "UTF-8"),
						keys[0], keys[1]);

				String acceptHeader = SecurityUtils.getSettingForApp(app, "security.oauth.accept_header", "");
				HttpPost tokenPost = new HttpPost(SecurityUtils.getSettingForApp(app, "security.oauth.token_url", ""));
				tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
				tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
				if (!StringUtils.isBlank(acceptHeader)) {
					tokenPost.setHeader(HttpHeaders.ACCEPT, acceptHeader);
				}

				try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
					if (resp1 != null && resp1.getEntity() != null) {
						Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
						if (token != null && token.containsKey("access_token")) {
							userAuth = getOrCreateUser(app, (String) token.get("access_token"));
						}
						EntityUtils.consumeQuietly(resp1.getEntity());
					}
				}
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
65737
@Override
    public boolean isUserInRole(String role, IExtendedRequest req) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "isUserInRole role = " + role);
        }

        if (role == null)
            return false;
        Subject subject = subjectManager.getCallerSubject();
        if (subject == null) {
            return false;
        }

        return wasch.isUserInRole(role, req, subject);

    }
470815
@Override
    public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException {
        User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password);
        if(u != null) {
            Authentication auth;
            try {
                UserDetails userDetails = u.getUserDetailsForImpersonation();
                auth = u.impersonate(userDetails);

                SecurityListener.fireAuthenticated(userDetails);
            } catch (UsernameNotFoundException x) {
                // The token was valid, but the impersonation failed. This token is clearly not his real password,
                // so there's no point in continuing the request processing. Report this error and abort.
                LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x);
                throw new ServletException(x);
            } catch (DataAccessException x) {
                throw new ServletException(x);
            }

            req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true);
            return auth;
        }
        return null;
    }
723895
public static boolean isWorkplaceUser(HttpServletRequest req) {

        HttpSession session = req.getSession(false);
        if (session != null) {
            // if a session is available, check for a workplace configuration
            CmsWorkplaceSettings workplaceSettings = (CmsWorkplaceSettings)session.getAttribute(
                CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS);
            return ((null != workplaceSettings) && !workplaceSettings.getUser().isGuestUser());
        }
        // no session means no workplace use
        return false;
    }
321533
public void handleRequest(ServletRequest req, ServletResponse res) throws Exception
	{
	    IServletWrapper target = this.cacheTarget;

	    if (target != null) {
	        try {
	            webapp.getFilterManager().invokeFilters((HttpServletRequest) req, (HttpServletResponse) res, webapp, target, CollaboratorHelper.allCollabEnum);
	        } catch (Throwable th){
	            if((com.ibm.ws.webcontainer.osgi.WebContainer.getServletContainerSpecLevel() >= 31) && th instanceof IOException){
	                if((th.getMessage()!= null) && th.getMessage().contains("SRVE0918E")){
	                    // dont do anything
	                    // we have already given chance to servlet and filters to handle it
	                    // this is application error but should not be returned to client.
	                    logger.logp(Level.FINE, CLASS_NAME, "handleRequest", "donothandleexception SRVE0918E");   
	                    return;
	                }
	            }
	            WebApp webapp = this.webapp;
	            if (webapp == null) {
	                FFDCFilter.processException(th, getClass().getName(), "83");
	            } else {
	                webapp.handleException(th, req, res, this);
	            }
	        }
	    }
	    else
	        throw InvalidCacheTargetException.instance();

	}
811682
private void requestAuthorization(HttpServletResponse resp) throws IOException {

        // Authorisation is required for the requested action.
        resp.setHeader(CmsRequestUtil.HEADER_WWW_AUTHENTICATE, "Basic realm=\"" + BASIC_REALM + "\"");

        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
835791
public ValidationSessionInfo checkAuth(ValidationLoginInfo info, HttpServletRequest req, HttpServletResponse res) {

        if (info.getToken() == null || info.getToken().isEmpty()) {
            throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED);
        }
        if (this.validationConfig.getAuthToken() == null) {
            throw new ValidationLibException("Sever authkey is not helper ", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        if (validaitonSessionCheckAndRemake(info.getToken())) {
            return this.createSession(req, res);
        }

        if (!this.validationConfig.getAuthToken().equals(info.getToken())) {
            throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED);
        }
        req.getSession();

        return this.createSession(req, res);
    }
837447
public boolean isAuthorized(HttpServletRequest req) {
		if(all)return true;
		if(roles!=null) {
			for(String srole : roles) {
				if(req.isUserInRole(srole)) return true;
			}
		}
		return false;
	}
513803
@Override
    public AuthenticationStatus authenticate(HttpServletRequest req, HttpServletResponse res, AuthenticationParameters params) {
        AuthenticationStatus authStatus = AuthenticationStatus.SEND_FAILURE;
        req.setAttribute(JavaEESecConstants.SECURITY_CONTEXT_AUTH_PARAMS, params);
        try {
            boolean result = req.authenticate(res);
            if (result) {
                authStatus = AuthenticationStatus.SUCCESS;
            } else {
//TODO some error handling.
            }
        } catch (Exception e) {
//TODO need to handle error.
            e.printStackTrace();
        }
        return authStatus;
    }
640541
@ExceptionHandler(Exception.class)
    public ModelAndView handleUnauthorizedServiceException(final HttpServletRequest req, final Exception ex) {
        return WebUtils.produceUnauthorizedErrorView();
    }
256707
void validate() throws ApplicationUnavailableException,
			AuthenticationException {
		V1ConnectionValidator validator = new V1ConnectionValidator(
				applicationPath, username, password, proxySettings);

		for (String key : customHttpHeaders.keySet()) {
			validator.getCustomHttpHeaders().put(key,
					customHttpHeaders.get(key));
		}

		try {
			validator.checkConnection();
		} catch (ConnectionException e) {
			throw new ApplicationUnavailableException(
					"Unable to connect to VersionOne.", e);
		}

		try {
			validator.checkAuthentication();
		} catch (ConnectionException e) {
			throw new AuthenticationException("Invalid username or password.",
					e);
		}
	}
1313993
private void checkHttpMethod(R pRequest) {
        if (!restrictor.isHttpMethodAllowed(pRequest.getHttpMethod())) {
            throw new SecurityException("HTTP method " + pRequest.getHttpMethod().getMethod() +
                    " is not allowed according to the installed security policy");
        }
    }
660352
private boolean handleCaseSensitivityCheck(String path, boolean checkWEBINF) throws IOException {
        if (System.getSecurityManager() != null) {
            final String tmpPath = path;
            final boolean tmpCheckWEBINF = checkWEBINF; //PK81387
            try {
                return ((Boolean) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws IOException {
                        return _handleCaseSensitivityCheck(tmpPath, tmpCheckWEBINF); //PK81387 added tmpCheckWEBINF param
                    }
                })).booleanValue();
            } catch (PrivilegedActionException pae) {
                throw (IOException) pae.getException();
            }
        } else {
            return (_handleCaseSensitivityCheck(path, checkWEBINF)).booleanValue(); //PK81387 added checkWEBINF param
        }
    }
259137
@POST
  @Path("/db/{authorizerName}/users/{userName}")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  @ResourceFilters(BasicSecurityResourceFilter.class)
  public Response createUser(
      @Context HttpServletRequest req,
      @PathParam("authorizerName") final String authorizerName,
      @PathParam("userName") String userName
  )
  {
    return resourceHandler.createUser(authorizerName, userName);
  }
1152389
@GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/id/{userId}")
    @Description("Returns the user having the given ID.")
    public PrincipalUserDto getUserById(@Context HttpServletRequest req,
        @PathParam("userId") final BigInteger userId) {
        if (userId == null || userId.compareTo(BigInteger.ZERO) < 1) {
            throw new WebApplicationException("User Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
        }

        PrincipalUser remoteUser = validateAndGetOwner(req, null);
        PrincipalUser user = _uService.findUserByPrimaryKey(userId);

        if (user != null) {
            super.validateResourceAuthorization(req, user, remoteUser);
            return PrincipalUserDto.transformToDto(user);
        }
        throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
    }