com.sun.jersey.api.core.HttpContext Java Examples

The following examples show how to use com.sun.jersey.api.core.HttpContext. 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: BasicAuthenticationProvider.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public AuthenticationVO getValue(HttpContext c) {
	String authHeaderValue = c.getRequest().getHeaderValue(HttpHeaders.AUTHORIZATION);
	String[] credentials = null;
	if (authHeaderValue != null) {
		credentials = JsUtil.decodeBase64(authHeaderValue.replaceFirst("[B|b]asic ", "")).split(":", 2);
	}
	AuthenticationVO result;
	if (credentials != null && credentials.length == 2) {
		result = new AuthenticationVO(credentials[0], credentials[1], null, WebUtil.getRemoteHost(request));
	} else {
		result = new AuthenticationVO();
		result.setHost(WebUtil.getRemoteHost(request));
	}
	return result;
}
 
Example #2
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Get the edOrg and public list response.
 *
 * @param context - the http request context
 * @return - the jax-rs response to send back
 */
Response getPublicAndEdOrgListResponse(final HttpContext context) {

    List<String> userEdOrgs = retrieveUserAssociatedEdOrgs();

    String appId = appAuthHelper.getApplicationId();

    List<String> appAuthorizedUserEdOrgs = getApplicationAuthorizedUserEdOrgs(userEdOrgs, appId);
    if (appAuthorizedUserEdOrgs.size() == 0) {
        logSecurityEvent("No authorized EdOrgs for application:" + appId);
        LOG.info("No authorized EdOrgs for application: {}", appId);
        return Response.status(Status.NOT_FOUND).build();
    }

    List<String> authorizedUserSEdOrgs = new LinkedList<String>();
    authorizedUserSEdOrgs.addAll(appAuthorizedUserEdOrgs);

    logSecurityEvent("Successfully retrieved edOrgs and public list for " + appId);
    return assembleLinksResponse(context, appId, authorizedUserSEdOrgs);
}
 
Example #3
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Stream a delta public extract response.
 *
 * @param context - HTTP context of request
 * @param request - HTTP servlet request for public bulk extract file
 * @param date the date of the delta
 *
 * @return A response with a delta extract file.
 */
@GET
@Path("extract/public/delta/{date}")
@RightsAllowed({ Right.BULK_EXTRACT })
public Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context,
                          @PathParam("date") String date) {
    logSecurityEvent("Received request to stream public delta bulk extract data");
    if (deltasEnabled) {
        LOG.info("Retrieving delta public bulk extract at date {}", date);

        if (date == null || date.isEmpty()) {
            logSecurityEvent("Failed delta request, missing date");
            throw new IllegalArgumentException("date cannot be missing");
        }

        validateRequestCertificate(request);

        return getPublicExtractResponse(context.getRequest(), date);

    }
    logSecurityEvent("Failed request for Edorg delta bulk extract data");
    return Response.status(404).build();
}
 
Example #4
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Send an edOrg private data extract.
 *
 * @param context - HTTP context of request
 * @param request - HTTP servlet request for public bulk extract file
 * @param edOrgId - The uuid of the edOrg to get the extract
 *
 * @return - A response with an edOrg tar file
 */
@GET
@Path("extract/{edOrgId}")
@RightsAllowed({ Right.BULK_EXTRACT })
public Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId) {
    logSecurityEvent("Received request to stream Edorg data");

    if (edOrgId == null || edOrgId.isEmpty()) {
        logSecurityEvent("Failed request to stream edOrg data, missing edOrgId");
        throw new IllegalArgumentException("edOrgId cannot be missing");
    }

    validateRequestCertificate(request);
    validateCanAccessEdOrgExtract(edOrgId);

    return getEdOrgExtractResponse(context.getRequest(), edOrgId, null);
}
 
Example #5
Source File: InstrumentedRequestDispatcher.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public void dispatch(Object resource, HttpContext httpContext) {
    final long start = registry.clock().wallTime();
    String callerId = CallerContextFilter.getCurrentCallerAddress().orElse("UNKNOWN");
    try {
        underlying.dispatch(resource, httpContext);
        clientInvocationMetrics.registerSuccess(callerId, tags, registry.clock().wallTime() - start);
    } catch (Exception e) {
        clientInvocationMetrics.registerFailure(callerId, tags, registry.clock().wallTime() - start);
        if (config.isJaxrsErrorLoggingEnabled()) {
            logger.error(generateRequestResponseErrorMessage(httpContext, e));
        }
        throw e;
    }
}
 
Example #6
Source File: InstrumentedRequestDispatcher.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private String generateRequestResponseErrorMessage(HttpContext context, Exception e) {
    StringBuilder result = new StringBuilder();
    HttpRequestContext request = context.getRequest();
    HttpResponseContext response = context.getResponse();
    result.append("An error occurred during an HTTP request:\r\n");
    if (request != null) {
        String bodyLengthString = request.getHeaderValue("Content-Length");
        result.append("Request Path: " + request.getMethod().toUpperCase() + " " + request.getRequestUri().toString() + "\r\n");
        result.append("Request Content-Length: " + bodyLengthString + "\r\n");
        result.append("Request Headers:\r\n" + request.getRequestHeaders()
                .entrySet()
                .stream()
                .map(entry -> "\t" + entry.getKey() + ": " + entry.getValue() + "\r\n")
                .collect(Collectors.joining())
        );

        long bodyLength = Strings.isNullOrEmpty(bodyLengthString) ? 0 : Long.parseLong(bodyLengthString);
        if (bodyLength > 0 && ((ContainerRequest) request).getEntityInputStream().markSupported()) {
            try {
                ((ContainerRequest) request).getEntityInputStream().reset();
                result.append("Request Body:\r\n" + request.getEntity(String.class) + "\r\n");
            } catch (Exception ignore) {
            }
        }
    }

    result.append("Error response http code: " + response.getStatus() + "\r\n");
    result.append("Error message: " + e.getMessage() + "\r\n");
    result.append("Error stack trace :\r\n" + Throwables.getStackTraceAsString(e) + "\r\n");

    return result.toString();
}
 
Example #7
Source File: UserProvider.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public UserGroupInformation getValue(final HttpContext context) {
  final Configuration conf = (Configuration) servletcontext
      .getAttribute(JspHelper.CURRENT_CONF);
  try {
    return JspHelper.getUGI(servletcontext, request, conf,
        AuthenticationMethod.KERBEROS, false);
  } catch (IOException e) {
    throw new SecurityException(
        SecurityUtil.FAILED_TO_GET_UGI_MSG_HEADER + " " + e, e);
  }
}
 
Example #8
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Stream a delta response.
 *
 * @param context - HTTP context of request
 * @param request - HTTP servlet request for public bulk extract file
 * @param date the date of the delta
 * @param edOrgId the uuid of the edOrg to get delta extract for
 *
 * @return A response with a delta extract file.
 */
@GET
@Path("extract/{edOrgId}/delta/{date}")
@RightsAllowed({ Right.BULK_EXTRACT })
public Response getDelta(@Context HttpServletRequest request, @Context HttpContext context,
                         @PathParam("edOrgId") String edOrgId, @PathParam("date") String date) {
    logSecurityEvent("Received request to stream Edorg delta bulk extract data");
    if (deltasEnabled) {
        LOG.info("Retrieving delta bulk extract for {}, at date {}", edOrgId, date);
        if (edOrgId == null || edOrgId.isEmpty()) {
            logSecurityEvent("Failed delta request, missing edOrgId");
            throw new IllegalArgumentException("edOrgId cannot be missing");
        }
        if (date == null || date.isEmpty()) {
            logSecurityEvent("Failed delta request, missing date");
            throw new IllegalArgumentException("date cannot be missing");
        }

        validateRequestCertificate(request);

        validateCanAccessEdOrgExtract(edOrgId);

        return getEdOrgExtractResponse(context.getRequest(), edOrgId, date);

    }
    logSecurityEvent("Failed request for Edorg delta bulk extract data");
    return Response.status(404).build();
}
 
Example #9
Source File: JerseyRequestModuleProvidesTest.java    From dagger-servlet with Apache License 2.0 5 votes vote down vote up
@Inject
public RequestProvidesResource(HttpContext httpContext, UriInfo uriInfo, ExtendedUriInfo extendedUriInfo,
                               HttpRequestContext httpRequestContext, HttpHeaders httpHeaders,
                               Request request, SecurityContext securityContext,
                               HttpResponseContext httpResponseContext) {
    assertNotNull(httpContext);
    assertNotNull(uriInfo);
    assertNotNull(extendedUriInfo);
    assertNotNull(httpRequestContext);
    assertNotNull(httpHeaders);
    assertNotNull(request);
    assertNotNull(securityContext);
    assertNotNull(httpResponseContext);
}
 
Example #10
Source File: UserProvider.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public UserGroupInformation getValue(final HttpContext context) {
  final Configuration conf = (Configuration) servletcontext
      .getAttribute(JspHelper.CURRENT_CONF);
  try {
    return JspHelper.getUGI(servletcontext, request, conf,
        AuthenticationMethod.KERBEROS, false);
  } catch (IOException e) {
    throw new SecurityException(
        SecurityUtil.FAILED_TO_GET_UGI_MSG_HEADER + " " + e, e);
  }
}
 
Example #11
Source File: UserProvider.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
public String getValue(HttpContext arg0) {
  final List<String> usernames = arg0.getRequest().getQueryParameters().get("user");
  if (usernames.isEmpty()) {
    return null;
  }
  return usernames.get(0);
}
 
Example #12
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Send a tenant public data full extract.
 *
 * @param context - HTTP context of request
 * @param request - HTTP servlet request for public bulk extract file
 *
 * @return - A response with a public extract tar file
 */
@GET
@Path("extract/public")
@RightsAllowed({ Right.BULK_EXTRACT })
public Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request) {
    logSecurityEvent("Received request to stream public data");

    validateRequestCertificate(request);

    return getPublicExtractResponse(context.getRequest(), null);
}
 
Example #13
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Send the list of BE file links for all edOrgs and public data for which the calling user and application have access.
 *
 * @param context - HTTP context of request
 * @param request - HTTP servlet request for public bulk extract file
 *
 * @return A response with the complete list of BE file links for all edOrgs and public data for this user/app.
 *
 * @throws Exception On Error.
 */
@GET
@Path("extract/list")
@RightsAllowed({ Right.BULK_EXTRACT })
public Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context) throws Exception {
    LOG.info("Received request for list of links for all edOrgs and public data for this user/app");
    logSecurityEvent("Received request for list of links for all edOrgs and public data for this user/app");
    validateRequestAndApplicationAuthorization(request);

    logSecurityEvent("Successful request for list of links for all edOrgs and public data for this user/app");
    return getPublicAndEdOrgListResponse(context);
}
 
Example #14
Source File: HmacAuthProvider.java    From jersey-hmac-auth with Apache License 2.0 4 votes vote down vote up
@Override
public T getValue(HttpContext httpContext) {
    return requestHandler.handle(httpContext.getRequest());
}
 
Example #15
Source File: JerseyRequestModule.java    From dagger-servlet with Apache License 2.0 4 votes vote down vote up
@Singleton
@Provides
public HttpContext provideHttpContext(WebApplication webApplication) {
    return webApplication.getThreadLocalHttpContext();
}
 
Example #16
Source File: BasicAuthBuilder.java    From eagle with Apache License 2.0 4 votes vote down vote up
public BasicAuthBuilder(AuthenticationConfig authConfig, Environment environment) {
    this.authConfig = authConfig;
    this.environment = environment;
    boolean needsCaching = authConfig.needsCaching();
    Authenticator<BasicCredentials, User> authenticator;
    String realm;
    if (authConfig.isEnabled()) {
        switch (authConfig.getMode()) {
            case "simple":
                authenticator = new SimpleBasicAuthenticator(authConfig.getSimple());
                realm = SIMPLE_MODE_REALM;
                break;
            case "ldap":
                authenticator = new LdapBasicAuthenticator(authConfig.getLdap());
                realm = LDAP_MODE_REALM;
                break;
            default:
                throw new IllegalArgumentException("Invalid auth mode " + authConfig.getMode());
        }
        if (needsCaching) {
            authenticator = cache(authenticator);
        }
        this.authenticator = authenticator;
        this.basicAuthProvider = new BasicAuthProvider<>(this.authenticator, realm);
    } else {
        this.authenticator = null;
        this.basicAuthProvider = new BasicAuthProvider<User>(null, "") {
            public Injectable<User> getInjectable(ComponentContext ic, Auth a, Parameter c) {
                return new AbstractHttpContextInjectable<User>() {
                    public User getValue(HttpContext c) {
                        User user =  new User();
                        user.setName("anonymous");
                        user.setFirstName("Anonymous User (auth: false)");
                        user.setRoles(Arrays.asList(User.Role.ALL_ROLES));
                        return user;
                    }
                };
            }
        };
    }
}
 
Example #17
Source File: SpringSecurityInjectable.java    From osiris with Apache License 2.0 3 votes vote down vote up
@Override
public BasicAuth getValue(HttpContext context) {
	
	

	Optional<BasicAuth> principal = Optional.absent();

	Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	
	
	

	if (auth != null && authenticationRequired) {

		String username = String.valueOf(auth.getPrincipal());
		String password = String.valueOf(auth.getCredentials());
		String api_key = String.valueOf(context.getRequest().getRequestHeader("api_key").get(0));

		if (username == null || username.isEmpty())
			throw new AuthException(Constants.REQUIRED_USERNAME);

		if (password == null || password.isEmpty())
			throw new AuthException(Constants.REQUIRED_PASSWORD);
		
		if (api_key == null || api_key.isEmpty())
			throw new AuthException(Constants.REQUIRED_APPID);

		@SuppressWarnings("unchecked")
		Authenticator<SpringSecurityCredentials, BasicAuth> authenticator = 
				(Authenticator<SpringSecurityCredentials, BasicAuth>) appContext.getBean(DropwizardAuthenticator.class.getName());

		SpringSecurityCredentials credentials = new SpringSecurityCredentials(username, password, api_key);

		principal = authenticate(authenticator, credentials);

	} else if (auth == null && authenticationRequired)
		throw new AuthException(Constants.REQUIRED_CREDENTIALS);

	return principal.get();
}
 
Example #18
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 3 votes vote down vote up
/**
 * Assemble the edOrgs and public HATEOAS links response.
 *
 * @param context
 *        Original HTTP Request Context.
 * @param appId
 *        Authorized application ID.
 * @param authorizedUserEdOrgs
 *        List of edOrgs authorized to use and authorizing the specified application.
 *
 * @return the jax-rs response to send back.
 */
private Response assembleLinksResponse(final HttpContext context, final String appId, final List<String> authorizedUserEdOrgs) {
    EntityBody list = assembleLinks(context, appId, authorizedUserEdOrgs);

    ResponseBuilder builder = Response.ok(list);
    builder.header("content-type", MediaType.APPLICATION_JSON + "; charset=utf-8");

    return builder.build();
}