Java源码示例:com.sun.jersey.api.core.HttpContext
示例1
@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;
}
示例2
/**
* 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);
}
示例3
/**
* 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();
}
示例4
/**
* 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);
}
示例5
@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);
}
}
示例6
@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;
}
}
示例7
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();
}
示例8
@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);
}
}
示例9
@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);
}
示例10
@Override
public String getValue(HttpContext arg0) {
final List<String> usernames = arg0.getRequest().getQueryParameters().get("user");
if (usernames.isEmpty()) {
return null;
}
return usernames.get(0);
}
示例11
/**
* 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);
}
示例12
/**
* 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);
}
示例13
/**
* 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();
}
示例14
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;
}
};
}
};
}
}
示例15
@Singleton
@Provides
public HttpContext provideHttpContext(WebApplication webApplication) {
return webApplication.getThreadLocalHttpContext();
}
示例16
@Override
public T getValue(HttpContext httpContext) {
return requestHandler.handle(httpContext.getRequest());
}
示例17
@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();
}
示例18
/**
* 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();
}