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

The following examples show how to use javax.servlet.http.HttpServletRequest#isSecure() . 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: MCRServlet3LoginServlet.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void think(MCRServletJob job) throws Exception {
    HttpServletRequest req = job.getRequest();
    HttpServletResponse res = job.getResponse();
    if (LOCAL_LOGIN_SECURE_ONLY && !req.isSecure()) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN, getErrorI18N("component.user2.login", "httpsOnly"));
        return;
    }
    String uid = getProperty(req, "uid");
    String pwd = getProperty(req, "pwd");
    String realm = getProperty(req, "realm");
    if (uid != null && pwd != null) {
        MCRSession session = MCRSessionMgr.getCurrentSession();
        req.login(uid, pwd);
        session.setUserInformation(new Servlet3ContainerUserInformation(session, realm));
        req.getSession().setAttribute(MCRRequestAuthenticationFilter.SESSION_KEY, Boolean.TRUE);
        LOGGER.info("Logged in: {}", session.getUserInformation().getUserID());
    }
}
 
Example 2
Source File: X509IdentityProvider.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts certificate-based credentials from an {@link HttpServletRequest}.
 *
 * The resulting {@link AuthenticationRequest} will be populated as:
 *  - username: principal DN from first client cert
 *  - credentials: first client certificate (X509Certificate)
 *  - details: proxied-entities chain (String)
 *
 * @param servletRequest the {@link HttpServletRequest} request that may contain credentials understood by this IdentityProvider
 * @return a populated AuthenticationRequest or null if the credentials could not be found.
 */
@Override
public AuthenticationRequest extractCredentials(HttpServletRequest servletRequest) {

    // only support x509 login when running securely
    if (!servletRequest.isSecure()) {
        return null;
    }

    // look for a client certificate
    final X509Certificate[] certificates = certificateExtractor.extractClientCertificate(servletRequest);
    if (certificates == null || certificates.length == 0) {
        return null;
    }

    // extract the principal
    final Object certificatePrincipal = principalExtractor.extractPrincipal(certificates[0]);
    final String principal = certificatePrincipal.toString();

    // extract the proxiedEntitiesChain header value from the servletRequest
    final String proxiedEntitiesChainHeader = servletRequest.getHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN);
    final X509AuthenticationRequestDetails details = new X509AuthenticationRequestDetails(proxiedEntitiesChainHeader, servletRequest.getMethod());

    return new AuthenticationRequest(principal, certificates[0], details);

}
 
Example 3
Source File: CourierRenderer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/** 
 * This method is a duplicate of {@link org.sakaiproject.util.RequestFilter#serverUrl(HttpServletRequest)}
 * Duplicated here from org.sakaiproject.util.web.Web.java so that 
 * the JSF tag library doesn't have a direct jar dependency on more of Sakai.
 */
private static String serverUrl(HttpServletRequest req)
{
	StringBuilder url = new StringBuilder();
	url.append(req.getScheme());
	url.append("://");
	url.append(req.getServerName());
	if (((req.getServerPort() != 80) && (!req.isSecure())) || ((req.getServerPort() != 443) && (req.isSecure())))
	{
		url.append(":");
		url.append(req.getServerPort());
	}

	return url.toString();
}
 
Example 4
Source File: ZTSImpl.java    From athenz with Apache License 2.0 5 votes vote down vote up
void validateRequest(HttpServletRequest request, final String principalDomain, final String caller,
                     boolean statusRequest) {
    
    // first validate if we're required process this over TLS only
    
    if (secureRequestsOnly && !request.isSecure()) {
        throw requestError(caller + "request must be over TLS", caller,
                ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
    }
    
    // second check if this is a status port so we can only
    // process on status requests
    
    if (statusPort > 0 && statusPort != httpPort && statusPort != httpsPort) {
        
        // non status requests must not take place on the status port
        
        if (!statusRequest && request.getLocalPort() == statusPort) {
            throw requestError("incorrect port number for a non-status request",
                    caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
        }
        
        // status requests must not take place on a non-status port
        
        if (statusRequest && request.getLocalPort() != statusPort) {
            throw requestError("incorrect port number for a status request",
                    caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
        }
    }
}
 
Example 5
Source File: X509AuthenticationFilter.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(final HttpServletRequest request) {
    // only suppport x509 login when running securely
    if (!request.isSecure()) {
        return null;
    }

    // look for a client certificate
    final X509Certificate[] certificates = certificateExtractor.extractClientCertificate(request);
    if (certificates == null) {
        return null;
    }

    return new X509AuthenticationRequestToken(request.getHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN), principalExtractor, certificates, request.getRemoteAddr());
}
 
Example 6
Source File: TopologySSEServlet.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType("text/event-stream");
    resp.setCharacterEncoding("UTF-8");

    AsyncContext asyncContext = req.startAsync();
    PrintWriter writer = resp.getWriter();

    TopologyListener topologyListener = new SSETopologyListener(writer, req.isSecure());

    ScheduledFuture keepAlive = this.keepAliveExecutor.scheduleAtFixedRate(
            new KeepAliveRunnable(writer, topologyListener),
            10,
            15,
            TimeUnit.SECONDS);
    asyncContext.setTimeout(0);
    asyncContext.addListener(new TopologyAsyncListener(topology, topologyListener, keepAlive));


    this.topology.addListener(topologyListener);
    String json = topologyToJson(req.isSecure());
    writer.write("event: topologyChange\n");
    writer.write("data: " + json);
    writer.flush();

}
 
Example 7
Source File: HstsFilter.java    From Alpine with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain)
        throws ServletException, IOException {

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) resp;

    if (request.isSecure()) {
        if (includeSubdomains) {
            response.setHeader("Strict-Transport-Security", "max-age=" + maxAge + "; includeSubDomains");
        } else {
            response.setHeader("Strict-Transport-Security", "max-age=" + maxAge + ";");
        }
    } else {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        final StringBuilder sb = new StringBuilder();
        sb.append("https://").append(request.getServerName());

        if (httpsPort != DEFAULT_HTTPS_PORT) {
            sb.append(":").append(httpsPort);
        }
        if (request.getContextPath() != null) {
            sb.append(request.getContextPath());
        }
        if (request.getServletPath() != null) {
            sb.append(request.getServletPath());
        }
        if (request.getPathInfo() != null) {
            sb.append(request.getPathInfo());
        }
        if (request.getQueryString() != null && request.getQueryString().length() > 0) {
            sb.append("?").append(request.getQueryString());
        }
        response.setHeader("Location", sb.toString());
        return;
    }
    chain.doFilter(request, response);
}
 
Example 8
Source File: XForwardedHeaderRequestWrapper.java    From knox with Apache License 2.0 5 votes vote down vote up
private static String getForwardedPort( HttpServletRequest request ) {
  String value = request.getHeader( X_FORWARDED_PORT );
  if( value == null ) {
    String forwardedHost = getForwardedHost( request );
    int separator = forwardedHost.indexOf(':');
    if ( separator > 0 ) {
        value = forwardedHost.substring(separator + 1, forwardedHost.length());
    } else {
        // use default ports
        value = request.isSecure() ? "443" : "80";
    }
  }
  return value;
}
 
Example 9
Source File: AccessResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.TEXT_PLAIN)
@Path("oidc/exchange")
@ApiOperation(
        value = "Retrieves a JWT following a successful login sequence using the configured OpenId Connect provider.",
        response = String.class,
        notes = NON_GUARANTEED_ENDPOINT
)
public Response oidcExchange(@Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) throws Exception {
    // only consider user specific access over https
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("User authentication/authorization is only supported when running over HTTPS.");
    }

    // ensure oidc is enabled
    if (!oidcService.isOidcEnabled()) {
        throw new IllegalStateException("OpenId Connect is not configured.");
    }

    final String oidcRequestIdentifier = getCookieValue(httpServletRequest.getCookies(), OIDC_REQUEST_IDENTIFIER);
    if (oidcRequestIdentifier == null) {
        throw new IllegalArgumentException("The login request identifier was not found in the request. Unable to continue.");
    }

    // remove the oidc request cookie
    removeOidcRequestCookie(httpServletResponse);

    // get the jwt
    final String jwt = oidcService.getJwt(oidcRequestIdentifier);
    if (jwt == null) {
        throw new IllegalArgumentException("A JWT for this login request identifier could not be found. Unable to continue.");
    }

    // generate the response
    return generateOkResponse(jwt).build();
}
 
Example 10
Source File: AccessResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
@Path("/logout")
@ApiOperation(
        value = "Performs a logout for other providers that have been issued a JWT.",
        notes = NON_GUARANTEED_ENDPOINT
)
@ApiResponses(
        value = {
                @ApiResponse(code = 200, message = "User was logged out successfully."),
                @ApiResponse(code = 401, message = "Authentication token provided was empty or not in the correct JWT format."),
                @ApiResponse(code = 500, message = "Client failed to log out."),
        }
)
public Response logOut(@Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) {
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("User authentication/authorization is only supported when running over HTTPS.");
    }

    String userIdentity = NiFiUserUtils.getNiFiUserIdentity();

    if(userIdentity != null && !userIdentity.isEmpty()) {
        try {
            logger.info("Logging out user " + userIdentity);
            jwtService.logOut(userIdentity);
            return generateOkResponse().build();
        } catch (final JwtException e) {
            logger.error("Logout of user " + userIdentity + " failed due to: " + e.getMessage());
            return Response.serverError().build();
        }
    } else {
        return Response.status(401, "Authentication token provided was empty or not in the correct JWT format.").build();
    }
}
 
Example 11
Source File: RequestWrapper.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void parseProxyInfo(HttpServletRequest request) {
    secure = request.isSecure();
    scheme = request.getScheme();
    String forwardedProtocol = request.getHeader("x-forwarded-proto");
    if (!StringUtils.isEmpty(forwardedProtocol)) {
        proxied = true;
        scheme = forwardedProtocol.toLowerCase();
        secure = HTTPConstants.SCHEME_HTTPS.equals(scheme);
        String forwardedForInfo = request.getHeader("x-forwarded-for");
        remoteAddr = !StringUtils.isEmpty(forwardedForInfo) ? forwardedForInfo.trim().split(",")[0]
            : request.getRemoteAddr();
    }
}
 
Example 12
Source File: MCRLoginServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
protected void presentLoginForm(MCRServletJob job)
    throws IOException, TransformerException, SAXException, JAXBException {
    HttpServletRequest req = job.getRequest();
    HttpServletResponse res = job.getResponse();
    if (LOCAL_LOGIN_SECURE_ONLY && !req.isSecure()) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN, getErrorI18N("component.user2.login", "httpsOnly"));
        return;
    }

    String returnURL = getReturnURL(req);
    String formAction = req.getRequestURI();
    MCRLogin loginForm = new MCRLogin(MCRSessionMgr.getCurrentSession().getUserInformation(), returnURL,
        formAction);
    String uid = getProperty(req, "uid");
    String pwd = getProperty(req, "pwd");
    if (uid != null) {
        MCRUser user = MCRUserManager.login(uid, pwd);
        if (user == null) {
            res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            loginForm.setLoginFailed(true);
        } else {
            //user logged in
            // MCR-1154
            req.changeSessionId();
            LOGGER.info("user {} logged in successfully.", uid);
            res.sendRedirect(res.encodeRedirectURL(getReturnURL(req)));
            return;
        }
    }
    addFormFields(loginForm, job.getRequest().getParameter(REALM_URL_PARAMETER));
    getLayoutService().doLayout(req, res, new MCRJAXBContent<>(JAXBContext.newInstance(MCRLogin.class), loginForm));
}
 
Example 13
Source File: RemoteIpFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public XForwardedRequest(HttpServletRequest request) {
    super(request);
    this.localPort = request.getLocalPort();
    this.remoteAddr = request.getRemoteAddr();
    this.remoteHost = request.getRemoteHost();
    this.scheme = request.getScheme();
    this.secure = request.isSecure();
    this.serverPort = request.getServerPort();
    
    headers = new HashMap<String, List<String>>();
    for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
        String header = headerNames.nextElement();
        headers.put(header, Collections.list(request.getHeaders(header)));
    }
}
 
Example 14
Source File: TestRemoteIpFilter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testInvokeXforwardedHost() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("hostHeader", "x-forwarded-host");
    filterDef.addInitParameter("portHeader", "x-forwarded-port");
    filterDef.addInitParameter("protocolHeader", "x-forwarded-proto");

    MockHttpServletRequest request = new MockHttpServletRequest();
    // client ip
    request.setRemoteAddr("192.168.0.10");
    request.setRemoteHost("192.168.0.10");
    // protocol
    request.setSecure(false);
    request.setServerPort(8080);
    request.setScheme("http");
    // host and port
    request.getCoyoteRequest().serverName().setString("10.0.0.1");
    request.setHeader("x-forwarded-host", "example.com");
    request.setHeader("x-forwarded-port", "8443");
    request.setHeader("x-forwarded-proto", "https");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    // protocol
    String actualServerName = actualRequest.getServerName();
    Assert.assertEquals("postInvoke serverName", "example.com", actualServerName);

    String actualScheme = actualRequest.getScheme();
    Assert.assertEquals("postInvoke scheme", "https", actualScheme);

    int actualServerPort = actualRequest.getServerPort();
    Assert.assertEquals("postInvoke serverPort", 8443, actualServerPort);

    boolean actualSecure = actualRequest.isSecure();
    Assert.assertTrue("postInvoke secure", actualSecure);
}
 
Example 15
Source File: UserFilter.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds or refresh the given cookie.
 * @param request
 * @param response
 * @param stayLoggedInCookie
 */
public static void addStayLoggedInCookie(final HttpServletRequest request, final HttpServletResponse response,
    final Cookie stayLoggedInCookie)
{
  stayLoggedInCookie.setMaxAge(COOKIE_MAX_AGE);
  stayLoggedInCookie.setPath("/");
  if (request.isSecure() == true) {
    log.debug("Set secure cookie");
    stayLoggedInCookie.setSecure(true);
  } else {
    log.debug("Set unsecure cookie");
  }
  response.addCookie(stayLoggedInCookie); // Refresh cookie.
}
 
Example 16
Source File: Web.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Compute the URL that would return to this server based on the current
 * request. Note: this method is duplicated in the kernel/request
 * RequestFilter.java
 * 
 * @param req
 *            The request.
 * @return The URL back to this server based on the current request.
 */
public static String serverUrl(HttpServletRequest req) {
	String transport = null;
	int port = 0;
	boolean secure = false;

	// if force.url.secure is set (to a https port number), use https and
	// this port
	String forceSecure = System.getProperty("sakai.force.url.secure");
	int forceSecureInt = NumberUtils.toInt(forceSecure);
	if (forceSecureInt > 0 && forceSecureInt <= 65535) {
		transport = "https";
		port = forceSecureInt;
		secure = true;
	}
	// otherwise use the request scheme and port
	else {
		transport = req.getScheme();
		port = req.getServerPort();
		secure = req.isSecure();
	}

	StringBuilder url = new StringBuilder();
	url.append(transport);
	url.append("://");
	url.append(req.getServerName());
	if (((port != 80) && (!secure)) || ((port != 443) && secure)) {
		url.append(":");
		url.append(port);
	}

	return url.toString();
}
 
Example 17
Source File: CustomHeaderWriter.java    From guardedbox with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void writeHeaders(
        HttpServletRequest request,
        HttpServletResponse response) {

    // HSTS and Expect-CT.
    if (request.isSecure() && !dev) {
        if (!StringUtils.isEmpty(headersProperties.getStrictTransportSecurityHeader()))
            response.setHeader(STRICT_TRANSPORT_SECURITY.getHeaderName(), headersProperties.getStrictTransportSecurityHeader());
        if (!StringUtils.isEmpty(headersProperties.getExpectCtHeader()))
            response.setHeader(EXPECT_CT.getHeaderName(), headersProperties.getExpectCtHeader());
    }

    // Content Security Policy.
    if (!dev && !StringUtils.isEmpty(headersProperties.getContentSecurityPolicyHeader()))
        response.setHeader(CONTENT_SECURITY_POLICY.getHeaderName(), headersProperties.getContentSecurityPolicyHeader());

    // Cache Control.
    String uri = request.getRequestURI();
    String uriExtension = uri.lastIndexOf(".") == -1 ? "" : uri.substring(uri.lastIndexOf(".") + 1);

    if (uri.startsWith(API_BASE_PATH) || NON_CACHEABLE_URI_EXTENSIONS.contains(uriExtension)) {
        if (!StringUtils.isEmpty(headersProperties.getCacheControlNonCacheableHeader()))
            response.setHeader(CACHE_CONTROL.getHeaderName(), headersProperties.getCacheControlNonCacheableHeader());
    } else if (CACHEABLE_URI_EXTENSIONS.contains(uriExtension)) {
        if (!StringUtils.isEmpty(headersProperties.getCacheControlCacheableHeader()))
            response.setHeader(CACHE_CONTROL.getHeaderName(), headersProperties.getCacheControlCacheableHeader());
    } else {
        if (!StringUtils.isEmpty(headersProperties.getCacheControlNonCacheableHeader()))
            response.setHeader(CACHE_CONTROL.getHeaderName(), headersProperties.getCacheControlNonCacheableHeader());
    }

    // Frame Options.
    if (!StringUtils.isEmpty(headersProperties.getFrameOptionsHeader()))
        response.setHeader(FRAME_OPTIONS.getHeaderName(), headersProperties.getFrameOptionsHeader());

    // XSS Protection.
    if (!StringUtils.isEmpty(headersProperties.getXssProtectionHeader()))
        response.setHeader(XSS_PROTECTION.getHeaderName(), headersProperties.getXssProtectionHeader());

    // Content Type Options.
    if (!StringUtils.isEmpty(headersProperties.getContentTypeOptionsHeader()))
        response.setHeader(CONTENT_TYPE_OPTIONS.getHeaderName(), headersProperties.getContentTypeOptionsHeader());

    // Referrer Policy.
    if (!StringUtils.isEmpty(headersProperties.getReferrerPolicyHeader()))
        response.setHeader(REFERRER_POLICY.getHeaderName(), headersProperties.getReferrerPolicyHeader());

    // Feature Policy.
    if (!StringUtils.isEmpty(headersProperties.getFeaturePolicyHeader()))
        response.setHeader(FEATURE_POLICY.getHeaderName(), headersProperties.getFeaturePolicyHeader());

}
 
Example 18
Source File: BasicAuthIdentityProvider.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
@Override
public AuthenticationRequest extractCredentials(HttpServletRequest servletRequest) {

    if (servletRequest == null) {
        logger.debug("Cannot extract user credentials from null servletRequest");
        return null;
    }

    // only support this type of login when running securely
    if (!servletRequest.isSecure()) {
        return null;
    }

    final String authorization = servletRequest.getHeader(AUTHORIZATION);
    if (authorization == null || !authorization.startsWith(BASIC)) {
        logger.debug("HTTP Basic Auth credentials not present. Not attempting to extract credentials for authentication.");
        return null;
    }

    AuthenticationRequest authenticationRequest;

    try {

        // Authorization: Basic {base64credentials}
        String base64Credentials = authorization.substring(BASIC.length()).trim();
        String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
        // credentials = username:password
        final String[] credentialParts = credentials.split(":", 2);
        String username = credentialParts[0];
        String password = credentialParts[1];

        authenticationRequest = new UsernamePasswordAuthenticationRequest(username, password);

    } catch (IllegalArgumentException | IndexOutOfBoundsException e) {
        logger.info("Failed to extract user identity credentials.");
        logger.debug("", e);
        return null;
    }

    return authenticationRequest;

}
 
Example 19
Source File: NiFiAnonymousAuthenticationFilter.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication attemptAuthentication(final HttpServletRequest request) {
    // return the anonymous authentication request for this http request
    return new NiFiAnonymousAuthenticationRequestToken(request.isSecure(), request.getRemoteAddr());
}
 
Example 20
Source File: EnvironmentFilter.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void doFilter(ServletRequest request,
                     ServletResponse response,
                     FilterChain chain)
    throws IOException, ServletException {

    HttpServletRequest hreq = new
                         RhnHttpServletRequest((HttpServletRequest)request);
    HttpServletResponse hres = new RhnHttpServletResponse(
                                            (HttpServletResponse)response,
                                            hreq);

    boolean sslAvail = ConfigDefaults.get().isSSLAvailable();

    // There are a list of pages that don't require SSL, that list should
    // be called out here.
    String path = hreq.getRequestURI();
    // Have to make this decision here, because once we pass the request
    // off to the next filter, that filter can do work that sends data to
    // the client, meaning that we can't redirect.
    if (RhnHelper.pathNeedsSecurity(nosslurls, path) &&
            !hreq.isSecure() && sslAvail) {
        if (log.isDebugEnabled()) {
            log.debug("redirecting to secure: " + path);
        }
        redirectToSecure(hreq, hres);
        return;
    }

    // Set request attributes we may need later
    HttpServletRequest req = (HttpServletRequest) request;
    request.setAttribute(RequestContext.REQUESTED_URI, req.getRequestURI());

    if (log.isDebugEnabled()) {
        log.debug("set REQUESTED_URI: " + req.getRequestURI());
    }

    // add messages that were put on the request path.
    addParameterizedMessages(req);

    // Done, go up chain
    chain.doFilter(hreq, hres);
}