Example usage for javax.servlet.http HttpServletRequest isSecure

List of usage examples for javax.servlet.http HttpServletRequest isSecure

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isSecure.

Prototype

public boolean isSecure();

Source Link

Document

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

Usage

From source file:org.ejbca.ra.RaAuthenticationHelper.java

/** Invoke once the session is started to prevent security leak via HTTP headers related. */
private void resetUnwantedHttpHeaders(final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) {
    // Ensure that we never send the JSESSIONID over an insecure (HTTP) connection
    // By default JBoss will send the JSESSIONID cookie over HTTP with the "Secure;" option. Since this is sent in clear from the server to the broswer
    // it does not really help security much that it is only sent over HTTPS from client to server.
    if (!httpServletRequest.isSecure()
            && !StringUtils.isEmpty(httpServletResponse.getHeader(HTTP_HEADER_SET_COOKIE))) {
        if (log.isDebugEnabled()) {
            log.debug("Preventing '" + HTTP_HEADER_SET_COOKIE
                    + "' HTTP header on insecure connection with value: "
                    + httpServletResponse.getHeader(HTTP_HEADER_SET_COOKIE));
        }//from   w  ww  .j  ava2  s . com
        httpServletResponse.setHeader(HTTP_HEADER_SET_COOKIE, "");
    }
    // Prevent sending the the X-Powered-By header e.g. "JSF/2.0"
    if (!StringUtils.isEmpty(httpServletResponse.getHeader(HTTP_HEADER_X_POWERED_BY))) {
        if (log.isDebugEnabled()) {
            log.debug("Preventing '" + HTTP_HEADER_X_POWERED_BY + "' HTTP header with value: "
                    + httpServletResponse.getHeader(HTTP_HEADER_X_POWERED_BY));
        }
        httpServletResponse.setHeader(HTTP_HEADER_X_POWERED_BY, "");
    }
}

From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java

private void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;/* w w w. j a v  a 2 s .  c o  m*/

    log.append("-- DUMP HttpServletRequest START").append("\n");
    log.append("Method             : ").append(request.getMethod()).append("\n");
    log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n");
    log.append("Scheme             : ").append(request.getScheme()).append("\n");
    log.append("IsSecure           : ").append(request.isSecure()).append("\n");
    log.append("Protocol           : ").append(request.getProtocol()).append("\n");
    log.append("ContextPath        : ").append(request.getContextPath()).append("\n");
    log.append("PathInfo           : ").append(request.getPathInfo()).append("\n");
    log.append("QueryString        : ").append(request.getQueryString()).append("\n");
    log.append("RequestURI         : ").append(request.getRequestURI()).append("\n");
    log.append("RequestURL         : ").append(request.getRequestURL()).append("\n");
    log.append("ContentType        : ").append(request.getContentType()).append("\n");
    log.append("ContentLength      : ").append(request.getContentLength()).append("\n");
    log.append("CharacterEncoding  : ").append(request.getCharacterEncoding()).append("\n");

    log.append("---- Headers START\n");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        hN = headerNames.nextElement();
        log.append("[" + hN + "]=");
        Enumeration<String> headers = request.getHeaders(hN);
        while (headers.hasMoreElements()) {
            log.append("[" + headers.nextElement() + "]");
        }
        log.append("\n");
    }
    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(IOUtils.toString(request.getInputStream(), "UTF-8")).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletRequest END \n");
}

From source file:org.apache.nifi.registry.web.api.AccessResource.java

@POST
@Consumes(MediaType.WILDCARD)//from  w w w  .j av a 2  s .  c  o m
@Produces(MediaType.TEXT_PLAIN)
@Path("/token/kerberos")
@ApiOperation(value = "Creates a token for accessing the REST API via Kerberos Service Tickets or SPNEGO Tokens (which includes Kerberos Service Tickets)", notes = "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, "
        + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header "
        + "in the format 'Authorization: Bearer <token>'.", response = String.class)
@ApiResponses({ @ApiResponse(code = 400, message = HttpStatusMessages.MESSAGE_400),
        @ApiResponse(code = 401, message = HttpStatusMessages.MESSAGE_401),
        @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409
                + " The NiFi Registry may not be configured to support login Kerberos credentials."),
        @ApiResponse(code = 500, message = HttpStatusMessages.MESSAGE_500) })
public Response createAccessTokenUsingKerberosTicket(@Context HttpServletRequest httpServletRequest) {

    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS");
    }

    // if not configured with custom identity provider, don't consider credentials
    if (!properties.isKerberosSpnegoSupportEnabled() || kerberosSpnegoIdentityProvider == null) {
        throw new IllegalStateException("Kerberos service ticket login not supported by this NiFi Registry");
    }

    AuthenticationRequest authenticationRequest = kerberosSpnegoIdentityProvider
            .extractCredentials(httpServletRequest);

    if (authenticationRequest == null) {
        throw new UnauthorizedException("The client credentials are missing from the request.")
                .withAuthenticateChallenge(kerberosSpnegoIdentityProvider.getUsageInstructions().getAuthType());
    }

    final String token;
    try {
        token = createAccessToken(kerberosSpnegoIdentityProvider, authenticationRequest);
    } catch (final InvalidCredentialsException ice) {
        throw new UnauthorizedException("The supplied client credentials are not valid.", ice)
                .withAuthenticateChallenge(kerberosSpnegoIdentityProvider.getUsageInstructions().getAuthType());
    }

    // build the response
    final URI uri = URI.create(generateResourceUri("access", "token"));
    return generateCreatedResponse(uri, token).build();

}

From source file:org.apache.nifi.registry.web.api.AccessResource.java

/**
 * Creates a token for accessing the REST API using a custom identity provider configured using NiFi Registry extensions.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)/*from  w  w  w . ja  v  a2s.  c o m*/
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.TEXT_PLAIN)
@Path("/token/identity-provider/test")
@ApiOperation(value = "Tests the format of the credentials against this identity provider without preforming authentication on the credentials to validate them.", notes = "The user credentials should be passed in a format understood by the custom identity provider as defined by 'GET /access/token/identity-provider/usage'.", response = String.class)
@ApiResponses({ @ApiResponse(code = 400, message = HttpStatusMessages.MESSAGE_400),
        @ApiResponse(code = 401, message = "The format of the credentials were not recognized by the currently configured identity provider."),
        @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409
                + " The NiFi Registry may not be configured to support login with customized credentials."),
        @ApiResponse(code = 500, message = HttpStatusMessages.MESSAGE_500) })
public Response testIdentityProviderRecognizesCredentialsFormat(
        @Context HttpServletRequest httpServletRequest) {

    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS");
    }

    // if not configured with custom identity provider, don't consider credentials
    if (identityProvider == null) {
        throw new IllegalStateException("Custom login not supported by this NiFi Registry");
    }

    final Class ipClazz = identityProvider.getClass();
    final String identityProviderName = StringUtils.isNotEmpty(ipClazz.getSimpleName())
            ? ipClazz.getSimpleName()
            : ipClazz.getName();

    // attempt to extract client credentials without authenticating them
    AuthenticationRequest authenticationRequest = identityProvider.extractCredentials(httpServletRequest);

    if (authenticationRequest == null) {
        throw new UnauthorizedException(
                "The format of the credentials were not recognized by the currently configured identity provider "
                        + "'" + identityProviderName + "'. "
                        + identityProvider.getUsageInstructions().getText()).withAuthenticateChallenge(
                                identityProvider.getUsageInstructions().getAuthType());
    }

    final String successMessage = identityProviderName
            + " recognized the format of the credentials in the HTTP request.";
    return generateOkResponse(successMessage).build();

}

From source file:org.apache.nifi.registry.web.api.AccessResource.java

/**
 * Creates a token for accessing the REST API using a custom identity provider configured using NiFi Registry extensions.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)/*from   w  ww . j  a va 2  s . com*/
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.TEXT_PLAIN)
@Path("/token/identity-provider")
@ApiOperation(value = "Creates a token for accessing the REST API via a custom identity provider.", notes = "The user credentials must be passed in a format understood by the custom identity provider, e.g., a third-party auth token in an HTTP header. "
        + "The exact format of the user credentials expected by the custom identity provider can be discovered by 'GET /access/token/identity-provider/usage'. "
        + "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, "
        + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header "
        + "in the format 'Authorization: Bearer <token>'.", response = String.class)
@ApiResponses({ @ApiResponse(code = 400, message = HttpStatusMessages.MESSAGE_400),
        @ApiResponse(code = 401, message = HttpStatusMessages.MESSAGE_401),
        @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409
                + " The NiFi Registry may not be configured to support login with customized credentials."),
        @ApiResponse(code = 500, message = HttpStatusMessages.MESSAGE_500) })
public Response createAccessTokenUsingIdentityProviderCredentials(
        @Context HttpServletRequest httpServletRequest) {

    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS");
    }

    // if not configured with custom identity provider, don't consider credentials
    if (identityProvider == null) {
        throw new IllegalStateException("Custom login not supported by this NiFi Registry");
    }

    AuthenticationRequest authenticationRequest = identityProvider.extractCredentials(httpServletRequest);

    if (authenticationRequest == null) {
        throw new UnauthorizedException("The client credentials are missing from the request.")
                .withAuthenticateChallenge(identityProvider.getUsageInstructions().getAuthType());
    }

    final String token;
    try {
        token = createAccessToken(identityProvider, authenticationRequest);
    } catch (InvalidCredentialsException ice) {
        throw new UnauthorizedException("The supplied client credentials are not valid.", ice)
                .withAuthenticateChallenge(identityProvider.getUsageInstructions().getAuthType());
    }

    // build the response
    final URI uri = URI.create(generateResourceUri("access", "token"));
    return generateCreatedResponse(uri, token).build();

}

From source file:com.devnexus.ting.web.controller.CallForPapersController.java

@RequestMapping(value = "/cfp", method = RequestMethod.POST)
public String addCfp(@Valid @ModelAttribute("cfpSubmission") CfpSubmissionForm cfpSubmission,
        BindingResult bindingResult, ModelMap model, HttpServletRequest request,
        RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/index";
    }//  ww w .  j  a  v a  2  s  .  c om
    if (request.getParameter("addSpeaker") != null) {
        prepareReferenceData(model, request.isSecure());
        CfpSubmissionSpeaker speaker = new CfpSubmissionSpeaker();
        speaker.setCfpSubmission(cfpSubmission);
        cfpSubmission.getSpeakers().add(speaker);
        return "/cfp";
    }

    if (request.getParameter("removeSpeaker") != null) {
        prepareReferenceData(model, request.isSecure());
        cfpSubmission.getSpeakers().remove(Integer.valueOf(request.getParameter("removeSpeaker")).intValue());
        return "/cfp";
    }

    final String reCaptchaEnabled = environment.getProperty("recaptcha.enabled");
    final String recaptchaPrivateKey = environment.getProperty("recaptcha.privateKey");

    if (Boolean.valueOf(reCaptchaEnabled)) {
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(recaptchaPrivateKey);

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
            ObjectError error = new ObjectError("error", "Please insert the correct CAPTCHA.");
            bindingResult.addError(error);
            prepareReferenceData(model, request.isSecure());
            return "/cfp";
        }
    }

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    final Event eventFromDb = businessService.getCurrentEvent();
    final CfpSubmission cfpSubmissionToSave = new CfpSubmission();

    if (cfpSubmission.getSpeakers().size() < 1) {
        ObjectError error = new ObjectError("error", "Please submit at least 1 speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    if (cfpSubmission.getPictureFiles().size() != cfpSubmission.getSpeakers().size()) {
        ObjectError error = new ObjectError("error", "Please submit a picture for each speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    cfpSubmissionToSave.setDescription(cfpSubmission.getDescription());
    cfpSubmissionToSave.setEvent(eventFromDb);

    cfpSubmissionToSave.setPresentationType(cfpSubmission.getPresentationType());
    cfpSubmissionToSave.setSessionRecordingApproved(cfpSubmission.isSessionRecordingApproved());
    cfpSubmissionToSave.setSkillLevel(cfpSubmission.getSkillLevel());
    cfpSubmissionToSave.setSlotPreference(cfpSubmission.getSlotPreference());
    cfpSubmissionToSave.setTitle(cfpSubmission.getTitle());
    cfpSubmissionToSave.setTopic(cfpSubmission.getTopic());

    int index = 0;
    for (CfpSubmissionSpeaker cfpSubmissionSpeaker : cfpSubmission.getSpeakers()) {

        final MultipartFile picture = cfpSubmission.getPictureFiles().get(index);
        InputStream pictureInputStream = null;

        try {
            pictureInputStream = picture.getInputStream();
        } catch (IOException e) {
            LOGGER.error("Error processing Image.", e);
            bindingResult.addError(new FieldError("cfpSubmission", "pictureFile", "Error processing Image."));
            prepareReferenceData(model, request.isSecure());
            return "/cfp";
        }

        if (pictureInputStream != null && picture.getSize() > 0) {
            SystemInformationUtils
                    .setSpeakerImage(
                            "CFP_" + cfpSubmissionSpeaker.getFirstName() + "_"
                                    + cfpSubmissionSpeaker.getLastName() + "_" + picture.getOriginalFilename(),
                            pictureInputStream);
        }

        index++;

        final CfpSubmissionSpeaker cfpSubmissionSpeakerToSave = new CfpSubmissionSpeaker();

        cfpSubmissionSpeakerToSave.setEmail(cfpSubmissionSpeaker.getEmail());
        cfpSubmissionSpeakerToSave.setBio(cfpSubmissionSpeaker.getBio());
        cfpSubmissionSpeakerToSave.setFirstName(cfpSubmissionSpeaker.getFirstName());
        cfpSubmissionSpeakerToSave.setGithubId(cfpSubmissionSpeaker.getGithubId());
        cfpSubmissionSpeakerToSave.setGooglePlusId(cfpSubmissionSpeaker.getGooglePlusId());
        cfpSubmissionSpeakerToSave.setLanyrdId(cfpSubmissionSpeaker.getLanyrdId());
        cfpSubmissionSpeakerToSave.setLastName(cfpSubmissionSpeaker.getLastName());
        cfpSubmissionSpeakerToSave.setLinkedInId(cfpSubmissionSpeaker.getLinkedInId());
        cfpSubmissionSpeakerToSave.setTwitterId(cfpSubmissionSpeaker.getTwitterId());
        cfpSubmissionSpeakerToSave.setLocation(cfpSubmissionSpeaker.getLocation());
        cfpSubmissionSpeakerToSave.setMustReimburseTravelCost(cfpSubmissionSpeaker.isMustReimburseTravelCost());
        cfpSubmissionSpeakerToSave.setTshirtSize(cfpSubmissionSpeaker.getTshirtSize());
        cfpSubmissionSpeakerToSave.setPhone(cfpSubmissionSpeaker.getPhone());
        cfpSubmissionSpeakerToSave.setCfpSubmission(cfpSubmissionToSave);
        cfpSubmissionToSave.getSpeakers().add(cfpSubmissionSpeakerToSave);

    }

    LOGGER.info(cfpSubmissionToSave.toString());
    businessService.saveAndNotifyCfpSubmission(cfpSubmissionToSave);

    return "redirect:/s/add-cfp-success";
}

From source file:org.apache.nifi.registry.web.api.AccessResource.java

/**
 * Creates a token for accessing the REST API.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)/*from w w  w.j a v  a 2  s  .com*/
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.TEXT_PLAIN)
@Path("/token")
@ApiOperation(value = "Creates a token for accessing the REST API via auto-detected method of verifying client identity claim credentials", notes = "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, "
        + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header "
        + "in the format 'Authorization: Bearer <token>'.", response = String.class)
@ApiResponses({ @ApiResponse(code = 400, message = HttpStatusMessages.MESSAGE_400),
        @ApiResponse(code = 401, message = HttpStatusMessages.MESSAGE_401),
        @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409
                + " The NiFi Registry may not be configured to support login with username/password."),
        @ApiResponse(code = 500, message = HttpStatusMessages.MESSAGE_500) })
public Response createAccessTokenByTryingAllProviders(@Context HttpServletRequest httpServletRequest) {

    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS");
    }

    List<IdentityProvider> identityProviderWaterfall = generateIdentityProviderWaterfall();

    String token = null;
    for (IdentityProvider provider : identityProviderWaterfall) {

        AuthenticationRequest authenticationRequest = identityProvider.extractCredentials(httpServletRequest);
        if (authenticationRequest == null) {
            continue;
        }
        try {
            token = createAccessToken(identityProvider, authenticationRequest);
            break;
        } catch (final InvalidCredentialsException ice) {
            logger.debug("{}: the supplied client credentials are invalid.",
                    identityProvider.getClass().getSimpleName());
            logger.debug("", ice);
        }

    }

    if (StringUtils.isEmpty(token)) {
        List<IdentityProviderUsage.AuthType> acceptableAuthTypes = identityProviderWaterfall.stream()
                .map(IdentityProvider::getUsageInstructions).map(IdentityProviderUsage::getAuthType)
                .filter(Objects::nonNull).distinct().collect(Collectors.toList());

        throw new UnauthorizedException(
                "Client credentials are missing or invalid according to all configured identity providers.")
                        .withAuthenticateChallenge(acceptableAuthTypes);
    }

    // build the response
    final URI uri = URI.create(generateResourceUri("access", "token"));
    return generateCreatedResponse(uri, token).build();
}

From source file:org.apache.nifi.web.api.AccessResource.java

/**
 * Creates a token for accessing the REST API via Kerberos ticket exchange / SPNEGO negotiation.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)/*from ww w . ja  va  2  s .c om*/
 */
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@Path("/kerberos")
@ApiOperation(value = "Creates a token for accessing the REST API via Kerberos ticket exchange / SPNEGO negotiation", notes = "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, "
        + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header "
        + "in the format 'Authorization: Bearer <token>'.", response = String.class)
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
        @ApiResponse(code = 401, message = "NiFi was unable to complete the request because it did not contain a valid Kerberos "
                + "ticket in the Authorization header. Retry this request after initializing a ticket with kinit and "
                + "ensuring your browser is configured to support SPNEGO."),
        @ApiResponse(code = 409, message = "Unable to create access token because NiFi is not in the appropriate state. (i.e. may not be configured to support Kerberos login."),
        @ApiResponse(code = 500, message = "Unable to create access token because an unexpected error occurred.") })
public Response createAccessTokenFromTicket(@Context HttpServletRequest httpServletRequest) {

    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS.");
    }

    // If Kerberos Service Principal and keytab location not configured, throws exception
    if (!properties.isKerberosSpnegoSupportEnabled() || kerberosService == null) {
        throw new IllegalStateException("Kerberos ticket login not supported by this NiFi.");
    }

    String authorizationHeaderValue = httpServletRequest.getHeader(KerberosService.AUTHORIZATION_HEADER_NAME);

    if (!kerberosService.isValidKerberosHeader(authorizationHeaderValue)) {
        final Response response = generateNotAuthorizedResponse()
                .header(KerberosService.AUTHENTICATION_CHALLENGE_HEADER_NAME,
                        KerberosService.AUTHORIZATION_NEGOTIATE)
                .build();
        return response;
    } else {
        try {
            // attempt to authenticate
            Authentication authentication = kerberosService.validateKerberosTicket(httpServletRequest);

            if (authentication == null) {
                throw new IllegalArgumentException(
                        "Request is not HTTPS or Kerberos ticket missing or malformed");
            }

            final String expirationFromProperties = properties.getKerberosAuthenticationExpiration();
            long expiration = FormatUtils.getTimeDuration(expirationFromProperties, TimeUnit.MILLISECONDS);
            final String identity = authentication.getName();
            expiration = validateTokenExpiration(expiration, identity);

            // create the authentication token
            final LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken(identity,
                    expiration, "KerberosService");

            // generate JWT for response
            final String token = jwtService.generateSignedToken(loginAuthenticationToken);

            // build the response
            final URI uri = URI.create(generateResourceUri("access", "kerberos"));
            return generateCreatedResponse(uri, token).build();
        } catch (final AuthenticationException e) {
            throw new AccessDeniedException(e.getMessage(), e);
        }
    }
}

From source file:flex.messaging.services.http.proxy.ProxyContextFilter.java

protected void setupTarget(ProxyContext context) {
    Target target = context.getTarget();
    String source = context.getUrl();
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();

    try {//from  ww w . j a  v a2 s  . c  o  m
        target.setUrl(new URL(source));
    } catch (MalformedURLException e) {
        try {
            //[Pete] Enhancement Req. 80172 - relative URLs from webroot (not
            //       webapp context root)
            if (clientRequest != null) {
                String baseurl = "http" + (clientRequest.isSecure() ? "s" : "") + "://"
                        + clientRequest.getServerName() + ":" + clientRequest.getServerPort();

                target.setUrl(new URL(baseurl + source));
            } else {
                ProxyException pe = new ProxyException();
                pe.setMessage(RELATIVE_NOT_SUPPORTED, new Object[] { source });
                throw pe;
            }
        } catch (MalformedURLException ex) {
            target.setUrl(null);
        }
    }

    if (target.getUrl() == null) {
        ProxyException pe = new ProxyException();
        pe.setMessage(INVALID_TARGET, new Object[] { source });
        throw pe;
    }

    target.setHTTPS(target.getUrl().getProtocol().equalsIgnoreCase("https"));
    target.setEncodedPath(target.getUrl().getPath());
    String queryStr = target.getUrl().getQuery();
    if (queryStr != null) {
        target.setEncodedPath(target.getEncodedPath() + ("?" + queryStr));
    }
    try {
        target.setEncodedPath(URIUtil.encodePathQuery(target.getEncodedPath()));
    } catch (URIException e) {
        // exception is thrown if the default charset is not supported.
        // proceed with the provided URL.
    }

    target.setHostConfig(new HostConfiguration());
    String targetHost = target.getUrl().getHost();
    int targetPort = target.getUrl().getPort();

    // Check for a custom protocol
    Protocol customProtocol = context.getProtocol();
    if (customProtocol != null) {
        target.getHostConfig().setHost(targetHost, targetPort, customProtocol);
    } else if (target.isHTTPS() && context.allowLaxSSL()) {
        target.getHostConfig().setHost(targetHost, targetPort, myhttps);
    } else {
        String targetProtocol = target.getUrl().getProtocol();
        target.getHostConfig().setHost(targetHost, targetPort, targetProtocol);
    }

    if (context.getConnectionManager() != null) {
        context.setHttpClient(new HttpClient(context.getConnectionManager()));
    } else {
        context.setHttpClient(new HttpClient());
    }

    // Determine if target domain matches this proxy's domain and port
    boolean localDomain = false;
    boolean localPort = false;
    if (clientRequest != null) {
        String proxyDomain = clientRequest.getServerName().contains(STRING_LOCALHOST) ? getResolvedLocalhost()
                : clientRequest.getServerName();
        String resolvedTargetHost = targetHost.contains(STRING_LOCALHOST) ? getResolvedLocalhost() : targetHost;
        if (proxyDomain.equalsIgnoreCase(resolvedTargetHost)) {
            localDomain = true;
            int proxyPort = clientRequest.getServerPort();
            localPort = proxyPort == targetPort;
        }
    }
    context.setLocalDomain(localDomain);
    context.setLocalPort(localPort);
}

From source file:org.apache.nifi.registry.web.api.AccessResource.java

/**
 * Creates a token for accessing the REST API.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)// w w  w  .  ja v  a  2s . c o m
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.TEXT_PLAIN)
@Path("/token/login")
@ApiOperation(value = "Creates a token for accessing the REST API via username/password", notes = "The user credentials must be passed in standard HTTP Basic Auth format. "
        + "That is: 'Authorization: Basic <credentials>', where <credentials> is the base64 encoded value of '<username>:<password>'. "
        + "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, "
        + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header "
        + "in the format 'Authorization: Bearer <token>'.", response = String.class, authorizations = {
                @Authorization("BasicAuth") })
@ApiResponses({ @ApiResponse(code = 400, message = HttpStatusMessages.MESSAGE_400),
        @ApiResponse(code = 401, message = HttpStatusMessages.MESSAGE_401),
        @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409
                + " The NiFi Registry may not be configured to support login with username/password."),
        @ApiResponse(code = 500, message = HttpStatusMessages.MESSAGE_500) })
public Response createAccessTokenUsingBasicAuthCredentials(@Context HttpServletRequest httpServletRequest) {

    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS");
    }

    // if not configured with custom identity provider, or if provider doesn't support HTTP Basic Auth, don't consider credentials
    if (identityProvider == null) {
        logger.debug(
                "An Identity Provider must be configured to use this endpoint. Please consult the administration guide.");
        throw new IllegalStateException(
                "Username/Password login not supported by this NiFi. Contact System Administrator.");
    }
    if (!(identityProvider instanceof BasicAuthIdentityProvider)) {
        logger.debug(
                "An Identity Provider is configured, but it does not support HTTP Basic Auth authentication. "
                        + "The configured Identity Provider must extend {}",
                BasicAuthIdentityProvider.class);
        throw new IllegalStateException(
                "Username/Password login not supported by this NiFi. Contact System Administrator.");
    }

    // generate JWT for response
    AuthenticationRequest authenticationRequest = identityProvider.extractCredentials(httpServletRequest);

    if (authenticationRequest == null) {
        throw new UnauthorizedException("The client credentials are missing from the request.")
                .withAuthenticateChallenge(IdentityProviderUsage.AuthType.OTHER);
    }

    final String token;
    try {
        token = createAccessToken(identityProvider, authenticationRequest);
    } catch (final InvalidCredentialsException ice) {
        throw new UnauthorizedException("The supplied client credentials are not valid.", ice)
                .withAuthenticateChallenge(IdentityProviderUsage.AuthType.OTHER);
    }

    // form the response
    final URI uri = URI.create(generateResourceUri("access", "token"));
    return generateCreatedResponse(uri, token).build();
}