Java Code Examples for javax.ws.rs.container.ContainerRequestContext#getHeaderString()

The following examples show how to use javax.ws.rs.container.ContainerRequestContext#getHeaderString() . 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: SampleAuthorizationFilter.java    From doctorkafka with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
  String userHeader = requestContext.getHeaderString(USER_HEADER);
  String groupsHeader = requestContext.getHeaderString(GROUPS_HEADER);
  DrKafkaSecurityContext ctx = null;
  if (userHeader != null && groupsHeader != null) {
    Set<String> userGroups = new HashSet<>(Arrays.asList(groupsHeader.split(",")));
    SetView<String> intersection = Sets.intersection(allowedAdminGroups, userGroups);
    if (intersection.size() > 0) {
      ctx = new DrKafkaSecurityContext(new UserPrincipal(userHeader), ADMIN_ROLE_SET);
      requestContext.setSecurityContext(ctx);
      LOG.info("Received authenticated request, created context:" + ctx);
      return;
    }
  }
  
  ctx = new DrKafkaSecurityContext(new UserPrincipal(userHeader), EMPTY_ROLE_SET);
  requestContext.setSecurityContext(ctx);
  LOG.info("Received annonymous request, bypassing authorizer");
}
 
Example 2
Source File: CORSFilter.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    // if there is no Origin header, then it is not a
    // cross origin request. We don't do anything.
    if (requestContext.getHeaderString("Origin") == null) {
        return;
    }
    // If it is a preflight request, then we add all
    // the CORS headers here.
    MultivaluedMap<String, Object> headers = responseContext.getHeaders();
    headers.add("Access-Control-Allow-Origin", requestContext.getHeaderString("Origin")); // for now, allows CORS requests coming from any source
    if (this.isPreflightRequest(requestContext)) {

        headers.add("Access-Control-Allow-Credentials", true);


        headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization");

        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");

        headers.add("Access-Control-Max-Age", 86400);
        headers.add("Vary", "Accept-Encoding, Origin");
        responseContext.setStatus(200);
    }
}
 
Example 3
Source File: RpcContextFilter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
    RpcContext.getContext().setRequest(request);

    // this only works for servlet containers
    if (request != null && RpcContext.getContext().getRemoteAddress() == null) {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
    }

    RpcContext.getContext().setResponse(ResteasyProviderFactory.getContextData(HttpServletResponse.class));

    String headers = requestContext.getHeaderString(DUBBO_ATTACHMENT_HEADER);
    if (headers != null) {
        for (String header : headers.split(",")) {
            int index = header.indexOf("=");
            if (index > 0) {
                String key = header.substring(0, index);
                String value = header.substring(index + 1);
                if (!StringUtils.isEmpty(key)) {
                    RpcContext.getContext().setAttachment(key.trim(), value.trim());
                }
            }
        }
    }
}
 
Example 4
Source File: CustomAuthorizationFilter.java    From microservice-integration with MIT License 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
    String userId = containerRequestContext.getHeaderString(SecurityConstants.USER_ID_IN_HEADER);

    if (StringUtils.isNotEmpty(userId)) {
        UserContext userContext = new UserContext(UUID.fromString(userId));
        userContext.setAccessType(AccessType.ACCESS_TYPE_NORMAL);
        log.info(userContext.toString());
        List<Permission> permissionList = feignAuthClient.getUserPermissions(userId);
        List<SimpleGrantedAuthority> authorityList = new ArrayList();
        for (Permission permission : permissionList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority();
            authority.setAuthority(permission.getPermission());
            authorityList.add(authority);
        }
        userContext.setAuthorities(authorityList);

        SecurityContextHolder.setContext(userContext);
    }
}
 
Example 5
Source File: CheckDomainFilter.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext reqContext) throws IOException {
    String domain = reqContext.getHeaderString(RESTHeaders.DOMAIN);
    if (domain != null && !SyncopeConstants.MASTER_DOMAIN.equals(domain)) {
        if (!domainHolder.getDomains().containsKey(domain)) {
            String message = "Domain '" + domain + "' not available";

            ErrorTO error = new ErrorTO();
            error.setStatus(Response.Status.NOT_FOUND.getStatusCode());
            error.setType(ClientExceptionType.NotFound);
            error.getElements().add(message);

            reqContext.abortWith(Response.status(Response.Status.NOT_FOUND).
                    entity(error).
                    header(HttpHeaders.CONTENT_TYPE,
                            reqContext.getAcceptableMediaTypes().isEmpty()
                            ? MediaType.APPLICATION_JSON
                            : reqContext.getAcceptableMediaTypes().get(0).toString()).
                    header(RESTHeaders.ERROR_CODE,
                            ClientExceptionType.NotFound.name()).
                    header(RESTHeaders.ERROR_INFO,
                            ClientExceptionType.NotFound.getInfoHeaderValue(message)).
                    build());
        }
    }
}
 
Example 6
Source File: RpcContextFilter.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
    RpcContext.getContext().setRequest(request);

    // this only works for servlet containers
    if (request != null && RpcContext.getContext().getRemoteAddress() == null) {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
    }

    RpcContext.getContext().setResponse(ResteasyProviderFactory.getContextData(HttpServletResponse.class));

    String headers = requestContext.getHeaderString(DUBBO_ATTACHMENT_HEADER);
    if (headers != null) {
        for (String header : headers.split(",")) {
            int index = header.indexOf("=");
            if (index > 0) {
                String key = header.substring(0, index);
                String value = header.substring(index + 1);
                if (!StringUtils.isEmpty(key)) {
                    RpcContext.getContext().setAttachment(key.trim(), value.trim());
                }
            }
        }
    }
}
 
Example 7
Source File: JwtAuthenticationFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String getEncodedJwtToken(ContainerRequestContext requestContext) {
    String auth = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
    String[] parts = auth == null ? null : auth.split(" ");
    if (parts == null || !expectedAuthScheme.equals(parts[0]) || parts.length != 2) {
        throw new JoseException(expectedAuthScheme + " scheme is expected");
    }
    return parts[1];
}
 
Example 8
Source File: SingularityWebhookAuthenticator.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private String extractAuthHeader(ContainerRequestContext context) {
  final String authHeaderValue = context.getHeaderString(HttpHeaders.AUTHORIZATION);

  if (Strings.isNullOrEmpty(authHeaderValue)) {
    throw WebExceptions.unauthorized(
      "No Authorization header present, please log in first"
    );
  } else {
    return authHeaderValue;
  }
}
 
Example 9
Source File: JWT_Client_IT.java    From agrest with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    String authHeaderVal = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    if (authHeaderVal == null
            || !authHeaderVal.startsWith("Bearer")
            || !authHeaderVal.contains(AUTH_TOKEN)) {
        System.out.println("No JWT token !");
        requestContext.setProperty("auth-failed", true);
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    }
}
 
Example 10
Source File: RequestLoggingFilter.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    MDCUtils.clear();
    requestContext.setProperty(REQUEST_EXECUTION_START, System.currentTimeMillis());

    String logRequestContext = requestContext.getHeaderString("log-request-context");
    if (logRequestContext == null) {
        logRequestContext = RandomUtils.randString(12);
    }
    MDCUtils.addRequestContext(logRequestContext);

    String logProcessContext = requestContext.getHeaderString("log-process-context");
    if (logProcessContext != null) {
        MDCUtils.addProcessContext(logProcessContext);
    }

    User user = null;
    try {
        user = userService.currentUser();
        if (user != null) {
            Integer userId = user.getId();
            if (userId != null) {
                MDCUtils.addUserId(Integer.toString(userId));
            }
        }
    } catch (Exception e) {
        // user not found, continue ...
    }

    UriInfo uriInfo = requestContext.getUriInfo();
    Request request = requestContext.getRequest();
    logger.info("Requested {} {}.", request.getMethod(), uriInfo.getRequestUri());

    if (logger.isTraceEnabled()) {
        MultivaluedMap<String, String> headers = requestContext.getHeaders();
        logger.trace("Headers: " + MapUtils.toString(headers));
        logger.trace("Entity: {}.", getEntityBody(requestContext));
        logger.trace("User principal name: {}", getUserPrincipalName(requestContext));
    }
}
 
Example 11
Source File: CrossOriginResourceSharingFilter.java    From trellis with Apache License 2.0 5 votes vote down vote up
private Map<String, String> handleSimpleRequest(final ContainerRequestContext req) {
    final Map<String, String> headers = new HashMap<>();
    final String origin = req.getHeaderString("Origin");

    // 6.1.1 Terminate if an Origin header is not present
    if (origin == null) {
        LOGGER.debug("CORS: No Origin header");
        return emptyMap();
    }

    // 6.1.2 Check for a case-sensitive match of the origin header string
    if (!originMatches(origin)) {
        LOGGER.debug("CORS: No Origin header match");
        return emptyMap();
    }

    // 6.1.3 Add the origin and credentials values
    headers.put("Access-Control-Allow-Origin", origin);
    if (credentials) {
        headers.put("Access-Control-Allow-Credentials", "true");
    }

    if (!exposedHeaders.isEmpty()) {
        headers.put("Access-Control-Expose-Headers", join(",", exposedHeaders));
    }

    return headers;
}
 
Example 12
Source File: DefaultMediaTypeFilter.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext reqCtx) {

    String acceptHdr = reqCtx.getHeaderString(ACCEPT);
    if (acceptHdr == null || acceptHdr.contains(MEDIA_TYPE_ANY)) {
        // replace it with JSON
        javax.ws.rs.core.MultivaluedMap<String, String> headers = reqCtx.getHeaders();
        headers.putSingle(ACCEPT, MEDIA_TYPE_JSON);
    }
}
 
Example 13
Source File: BasicAuthFilter.java    From trellis with Apache License 2.0 5 votes vote down vote up
private String getCredentials(final ContainerRequestContext ctx) {
    final String authHeader = ctx.getHeaderString(AUTHORIZATION);
    if (authHeader != null) {
        final String[] pair = authHeader.split(" ", 2);
        if (pair.length == 2 && pair[0].equalsIgnoreCase(BASIC_AUTH)) return pair[1];
    }
    return null;
}
 
Example 14
Source File: OAuthFilter.java    From trellis with Apache License 2.0 5 votes vote down vote up
private String getOAuthToken(final ContainerRequestContext ctx) {
    final String headerString = ctx.getHeaderString(AUTHORIZATION);
    if (headerString != null) {
        final String[] pair = headerString.split(" ", 2);
        if (pair.length == 2 && pair[0].equalsIgnoreCase(SCHEME)) return pair[1];
    }
    return null;
}
 
Example 15
Source File: AuthInterceptor.java    From enmasse with Apache License 2.0 5 votes vote down vote up
static Set<String> findGroups(ApiHeaderConfig apiHeaderConfig, ContainerRequestContext requestContext) {
    Set<String> groups = new HashSet<>();
    for (String groupHeader : apiHeaderConfig.getGroupHeaders()) {
        if (requestContext.getHeaderString(groupHeader) != null) {
            String grpHeader = requestContext.getHeaderString(groupHeader);
            groups.addAll(Arrays.asList(grpHeader.split(",")));
        }
    }
    return groups;
}
 
Example 16
Source File: CrossOriginResourceSharingFilter.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    String origin = requestContext.getHeaderString("Origin");
    if (ALLOWEDHOSTSLIST != null) {
        if (ALLOWEDHOSTSLIST.contains(origin)) {
            responseContext.getHeaders().putSingle("Access-Control-Allow-Origin", origin);
            responseContext.getHeaders().putSingle("Access-Control-Allow-Methods", ALLOWEDMETHODS);
            responseContext.getHeaders().putSingle("Access-Control-Allow-Headers", ALLOWEDHEADERS);
            responseContext.getHeaders().putSingle("Vary", "Origin");
        }
    }
}
 
Example 17
Source File: CrossOriginResourceSharingFilter.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    String origin = requestContext.getHeaderString("Origin");
    if (ALLOWEDHOSTSLIST != null) {
        if (ALLOWEDHOSTSLIST.contains(origin)) {
            responseContext.getHeaders().putSingle("Access-Control-Allow-Origin", origin);
            responseContext.getHeaders().putSingle("Access-Control-Allow-Methods", ALLOWEDMETHODS);
            responseContext.getHeaders().putSingle("Access-Control-Allow-Headers", ALLOWEDHEADERS);
            responseContext.getHeaders().putSingle("Vary", "Origin");
        }
    }
}
 
Example 18
Source File: CorsFilter.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	String origin = requestContext.getHeaderString(ORIGIN);
	if (origin == null) {
		return; // not CORS
	}
	URI originUri = toUriSafe(origin);
	if (!isValidOrigin(originUri)) {
		throw prepareCorsFailureRequest(new ForbiddenException("invalid origin"), requestContext);
	}
	if (sameOriginPolicy.isSameOrigin(requestContext, origin)) {
		return; // same origin => nothing to do
	}

	String accessControlRequestMethod = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_METHOD);
	if (!isValidAccessControlRequestMethod(accessControlRequestMethod)) {
		throw prepareCorsFailureRequest(new ForbiddenException("accessControlRequestMethod may not be empty"),
				requestContext);
	}
	String requestMethod = requestContext.getMethod();

	if (isPreflightRequest(requestMethod, accessControlRequestMethod)) {
		String accessControlRequestHeaders = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_HEADERS);
		WebApplicationException corsPreflightFailure = validateCorsPreflightRequest(origin,
				accessControlRequestMethod, accessControlRequestHeaders);
		if (corsPreflightFailure != null) {
			throw prepareCorsFailureRequest(corsPreflightFailure, requestContext);
		} else {
			requestContext.abortWith(
					buildPreflightResponse(origin, accessControlRequestMethod, accessControlRequestHeaders));
		}
	} else {
		WebApplicationException corsActualRequestFailure = validateCorsActualRequest(origin, requestMethod);
		if (corsActualRequestFailure != null) {
			throw prepareCorsFailureRequest(corsActualRequestFailure, requestContext);
		}
	}
}
 
Example 19
Source File: AuthenticationFilter.java    From clouditor with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
  // ignore filter for classes that do not have @RolesAllowed
  var rolesAllowed = resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);

  if (rolesAllowed == null) {
    return;
  }

  // ignore filter for OPTIONS requests (pre-flight requests)
  if (Objects.equals(requestContext.getMethod(), "OPTIONS")) {
    return;
  }

  String authorization = requestContext.getHeaderString(HEADER_AUTHORIZATION);

  if (authorization == null || authorization.isEmpty()) {
    // try cookies
    var cookie = requestContext.getCookies().get("authentication");
    if (cookie != null) {
      authorization = cookie.getValue();
    }
  }

  if (authorization == null || !authorization.startsWith("Bearer")) {
    throw new NotAuthorizedException("No token was specified");
  }

  String[] rr = authorization.split(" ");

  if (rr.length != 2) {
    throw new NotAuthorizedException("Invalid authentication format");
  }

  String token = rr[1];

  try {
    User user = authenticationService.verifyToken(token);

    LOGGER.debug(
        "Authenticated API access to {} as {}",
        requestContext.getUriInfo().getPath(),
        user.getName());

    var ctx = new UserContext(user, requestContext.getSecurityContext().isSecure());

    requestContext.setSecurityContext(ctx);

    var authorized = false;

    for (var role : rolesAllowed.value()) {
      if (ctx.isUserInRole(role)) {
        authorized = true;
        break;
      }
    }

    if (!authorized) {
      throw new ForbiddenException(
          "User " + user.getName() + " does not have appropriate role to view resource.");
    }

  } catch (NotAuthorizedException | ForbiddenException ex) {
    // log the error
    LOGGER.error(
        "API access to {} was denied: {}",
        requestContext.getUriInfo().getPath(),
        ex.getMessage());

    // re-throw it
    throw ex;
  }
}
 
Example 20
Source File: RestTracerAdapter.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
/**
 * 适配服务端filter
 *
 * @param requestContext ContainerRequestContext
 */
public static void serverFilter(ContainerRequestContext requestContext) {
    try {
        SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
        SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();
        if (serverSpan != null) {
            RpcInternalContext context = RpcInternalContext.getContext();

            context.setAttachment(RpcConstants.INTERNAL_KEY_SERVER_RECEIVE_TIME, RpcRuntimeContext.now());

            SofaResourceMethodInvoker resourceMethodInvoker = (SofaResourceMethodInvoker)
                    ((PostMatchContainerRequestContext) requestContext)
                        .getResourceMethod();

            SofaResourceFactory factory = resourceMethodInvoker.getResource();
            String serviceName = factory.getServiceName();
            String appName = factory.getAppName();

            if (serviceName == null) {
                serviceName = resourceMethodInvoker.getResourceClass().getName();
            }
            serverSpan.setTag(RpcSpanTags.SERVICE, serviceName);
            if (resourceMethodInvoker.getMethod() != null) {
                serverSpan.setTag(RpcSpanTags.METHOD, resourceMethodInvoker.getMethod().getName());
                //serverSend需要
                context.setAttachment(METHOD_TYPE_STRING, resourceMethodInvoker.getMethod());
            }

            serverSpan.setTag(RpcSpanTags.REMOTE_IP, context.getRemoteHostName()); // 客户端地址

            String remoteAppName = requestContext.getHeaderString(RemotingConstants.HEAD_APP_NAME);
            if (StringUtils.isNotBlank(remoteAppName)) {
                serverSpan.setTag(RpcSpanTags.REMOTE_APP, remoteAppName);
            }
            serverSpan.setTag(RpcSpanTags.PROTOCOL, RpcConstants.PROTOCOL_TYPE_REST);
            serverSpan.setTag(RpcSpanTags.INVOKE_TYPE, RpcConstants.INVOKER_TYPE_SYNC);
            if (appName == null) {
                appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME);
            }
            serverSpan.setTag(RpcSpanTags.LOCAL_APP, appName);
        }
    } catch (Throwable t) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("the process of rest tracer server filter occur error ", t);
        }
    }
}