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

The following are Jave code examples for showing how to use isSecure() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: nifi-registry   File: KerberosSpnegoIdentityProvider.java   View Source Code Vote up 6 votes
@Override
public AuthenticationRequest extractCredentials(HttpServletRequest request) {

    // Only support Kerberos authentication when running securely
    if (!request.isSecure()) {
        return null;
    }

    String headerValue = request.getHeader(AUTHORIZATION);

    if (!isValidKerberosHeader(headerValue)) {
        return null;
    }

    logger.debug("Detected 'Authorization: Negotiate header in request {}", request.getRequestURL());
    byte[] base64Token = headerValue.substring(headerValue.indexOf(" ") + 1).getBytes(StandardCharsets.UTF_8);
    byte[] kerberosTicket = Base64.decode(base64Token);
    if (kerberosTicket != null) {
        logger.debug("Successfully decoded SPNEGO/Kerberos ticket passed in Authorization: Negotiate <ticket> header.", request.getRequestURL());
    }

    return new AuthenticationRequest(null, kerberosTicket, authenticationDetailsSource.buildDetails(request));

}
 
Example 2
Project: nifi-registry   File: X509IdentityProvider.java   View Source Code Vote up 6 votes
/**
 * 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
    String proxiedEntitiesChainHeader = servletRequest.getHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN);

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

}
 
Example 3
Project: goodees   File: SecurityHeadersFilter.java   View Source Code Vote up 6 votes
@Override
public boolean doFilter(HttpServletRequest request, HttpServletResponse httpResponse,
        FilterChain chain) throws IOException, ServletException {
    if (disabled) {
        // skip the execution if disabled
        return true;
    }
    if (httpResponse.isCommitted()) {
        throw new ServletException("Response already committed");
    }

    // HSTS
    if (request.isSecure() && config.isHstsEnabled(request.getServerName())) {
        httpResponse.setHeader(HSTS_HEADER_NAME, hstsHeaderValue);
    }

    // anti click-jacking
    if (config.isAntiClickJackingEnabled()) {
        httpResponse.setHeader(ANTI_CLICK_JACKING_HEADER_NAME, antiClickJackingHeaderValue);
    }

    // Block content type sniffing
    if (config.isBlockContentTypeSniffingEnabled()) {
        httpResponse.setHeader(BLOCK_CONTENT_TYPE_SNIFFING_HEADER_NAME,
                BLOCK_CONTENT_TYPE_SNIFFING_HEADER_VALUE);
    }

    // cross-site scripting filter protection
    if (config.isXssProtectionEnabled()) {
        httpResponse.setHeader(XSS_PROTECTION_HEADER_NAME, XSS_PROTECTION_HEADER_VALUE);
    }
    return true; // invoke chain
}
 
Example 4
Project: webauthndemo   File: CreateSession.java   View Source Code Vote up 6 votes
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  // TODO Auto-generated method stub
  String currentUser = userService.getCurrentUser().getUserId();
  String rpId = (request.isSecure() ? "https://" : "http://") + request.getHeader("Host");
  PublicKeyCredentialRequestOptions assertion = new PublicKeyCredentialRequestOptions(rpId);
  SessionData session = new SessionData(assertion.challenge, rpId);
  session.save(currentUser);

  JsonObject assertionJson = new JsonObject();
  assertionJson.add("session", session.getJsonObject());


  response.setContentType("application/json");
  response.getWriter().println(assertionJson.toString());
}
 
Example 5
Project: google-actions   File: Oauth2BaseServlet.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	/* Only HTTPS traffic is allowed */
	if (!req.isSecure()) {
		resp.sendError(HttpServletResponse.SC_FORBIDDEN);
		log.warning("Received request http from: " + req.getRemoteAddr() + ":" + req.getRemoteHost());
		return;
	}
	request(req, resp);
}
 
Example 6
Project: tomcat7   File: RemoteIpFilter.java   View Source Code Vote up 5 votes
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 7
Project: tomcat7   File: TestRemoteIpFilter.java   View Source Code Vote up 5 votes
@Test
public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithDefaultValues() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("protocolHeader", "x-forwarded-proto");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setSecure(true);
    request.setScheme("https");
    request.setHeader("x-forwarded-for", "140.211.11.130");
    request.setHeader("x-forwarded-proto", "http");

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

    // VERIFY
    boolean actualSecure = actualRequest.isSecure();
    assertFalse("request must be unsecured as header x-forwarded-proto said it is http", actualSecure);

    String actualScheme = actualRequest.getScheme();
    assertEquals("scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);

}
 
Example 8
Project: oscm   File: ClosedMarketplaceFilter.java   View Source Code Vote up 5 votes
private String getRedirectToMkpAddress(HttpServletRequest httpRequest) {
    String result;
    if (httpRequest.isSecure()) {
        result = getRedirectMpUrlHttps(
                getConfigurationService(httpRequest));
    } else {
        result = getRedirectMpUrlHttp(getConfigurationService(httpRequest));
    }
    return result;
}
 
Example 9
Project: Equella   File: LogonSection.java   View Source Code Vote up 5 votes
@Override
public void beforeEvents(SectionInfo info)
{
	AutoLogin autoLogin = userService.getAttribute(AutoLogin.class);
	HttpServletRequest request = info.getRequest();
	if( autoLogin != null && request != null && autoLogin.isLoginViaSSL() && !request.isSecure() )
	{
		String href = info.getPublicBookmark().getHref();
		UriBuilder uriBuilder = UriBuilder.create(URI.create(href));
		uriBuilder.setScheme("https");
		info.forwardToUrl(uriBuilder.build().toString());
	}
}
 
Example 10
Project: lazycat   File: RemoteIpFilter.java   View Source Code Vote up 5 votes
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 11
Project: Equella   File: OAuthFilter.java   View Source Code Vote up 5 votes
@SuppressWarnings("nls")
@Override
public FilterResult filterRequest(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
{
	AutoLogin autoLogin = userService.getAttribute(AutoLogin.class);
	if( autoLogin != null && !request.isSecure() && autoLogin.isLoginViaSSL() )
	{
		throw new WebException(400, "ssl", LABEL_ERROR.getText());
	}
	return FilterResult.FILTER_CONTINUE;
}
 
Example 12
Project: apache-tomcat-7.0.73-with-comment   File: RemoteIpFilter.java   View Source Code Vote up 5 votes
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 13
Project: apache-tomcat-7.0.73-with-comment   File: TestRemoteIpFilter.java   View Source Code Vote up 5 votes
@Test
public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithCustomValues() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("protocolHeader", "x-forwarded-proto");
    filterDef.addInitParameter("remoteIpHeader", "x-my-forwarded-for");
    filterDef.addInitParameter("httpServerPort", "8080");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setSecure(true);
    request.setScheme("https");
    request.setHeader("x-my-forwarded-for", "140.211.11.130");
    request.setHeader("x-forwarded-proto", "http");

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

    // VERIFY
    boolean actualSecure = actualRequest.isSecure();
    assertFalse("request must be unsecured as header x-forwarded-proto said it is http", actualSecure);

    String actualScheme = actualRequest.getScheme();
    assertEquals("scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme);

    int actualServerPort = actualRequest.getServerPort();
    assertEquals("wrong http server port", 8080, actualServerPort);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
}
 
Example 14
Project: nifi-registry   File: AccessResource.java   View Source Code Vote up 4 votes
/**
 * 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)
 */
@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();

}
 
Example 15
Project: nifi-registry   File: AccessResource.java   View Source Code Vote up 4 votes
/**
 * 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)
 */
@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();

}
 
Example 16
Project: nifi-registry   File: AccessResource.java   View Source Code Vote up 4 votes
/**
 * Creates a token for accessing the REST API.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)
 */
@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
)
@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 createAccessTokenUsingFormLogin(@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();
}
 
Example 17
Project: nifi-registry   File: AccessResource.java   View Source Code Vote up 4 votes
@POST
@Consumes(MediaType.WILDCARD)
@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();

}
 
Example 18
Project: lemon   File: DefaultCookieSerializer.java   View Source Code Vote up 4 votes
private boolean isSecureCookie(HttpServletRequest request) {
	if (this.useSecureCookie == null) {
		return request.isSecure();
	}
	return this.useSecureCookie;
}
 
Example 19
Project: alfresco-remote-api   File: SOLRAuthenticationFilter.java   View Source Code Vote up 4 votes
public void doFilter(ServletContext context, ServletRequest request,
			ServletResponse response, FilterChain chain) throws IOException,
			ServletException
	{
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;

/*		if(secureComms == SecureCommsType.ALFRESCO)
		{
			// Need to get as a byte array because we need to read the request twice, once for authentication
			// and again by the web service.
			SOLRHttpServletRequestWrapper requestWrapper = new SOLRHttpServletRequestWrapper(httpRequest, encryptionUtils);
	
			if(logger.isDebugEnabled())
			{
				logger.debug("Authenticating " + httpRequest.getRequestURI());
			}
	
			if(encryptionUtils.authenticate(httpRequest, requestWrapper.getDecryptedBody()))
			{
				try
				{
					OutputStream out = response.getOutputStream();
	
					GenericResponseWrapper responseWrapper = new GenericResponseWrapper(httpResponse);
	
					// TODO - do I need to chain to other authenticating filters - probably not?
					// Could also remove sending of credentials with http request
					chain.doFilter(requestWrapper, responseWrapper);
	
					Pair<byte[], AlgorithmParameters> pair = encryptor.encrypt(KeyProvider.ALIAS_SOLR, null, responseWrapper.getData());
	
					encryptionUtils.setResponseAuthentication(httpRequest, httpResponse, responseWrapper.getData(), pair.getSecond());

					httpResponse.setHeader("Content-Length", Long.toString(pair.getFirst().length));
					out.write(pair.getFirst());
					out.close();
				}
				catch(Exception e)
				{
					throw new AlfrescoRuntimeException("", e);
				}
			}
			else
			{
				httpResponse.setStatus(401);
			}
		}
		else */if(secureComms == SecureCommsType.HTTPS)
		{
			if(httpRequest.isSecure())
			{
				// https authentication
				chain.doFilter(request, response);
			}
			else
			{
				throw new AlfrescoRuntimeException("Expected a https request");
			}
		}
		else
		{
			chain.doFilter(request, response);
		}
	}
 
Example 20
Project: nifi-registry   File: BasicAuthIdentityProvider.java   View Source Code Vote up 4 votes
@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;

}