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

The following examples show how to use javax.ws.rs.container.ContainerRequestContext#abortWith() . 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: ConnectionSecurityProvider.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    if (Boolean.TRUE.equals(request.getAttribute(SKIP))) {
        return;
    }

    final OnConnection onConnection = new OnConnection();
    onConnectionEvent.fire(onConnection);
    if (!onConnection.isValid()) {
        requestContext
                .abortWith(Response
                        .status(Response.Status.UNAUTHORIZED)
                        .entity(new ErrorPayload(UNAUTHORIZED, "Invalid connection credentials"))
                        .type(APPLICATION_JSON_TYPE)
                        .build());
    }
}
 
Example 2
Source File: CrossOriginResourceSharingFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();

    String httpMethod = (String)m.get(Message.HTTP_REQUEST_METHOD);
    if (HttpMethod.OPTIONS.equals(httpMethod)) {
        Response r = preflightRequest(m);
        if (r != null) {
            context.abortWith(r);
        }
    } else if (findResourceMethod) {
        Method method = getResourceMethod(m, httpMethod);
        simpleRequest(m, method);
    } else {
        m.getInterceptorChain().add(new CorsInInterceptor());
    }

}
 
Example 3
Source File: RolesAllowedDynamicFeatureImpl.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    if (!denyAll) {
        // TODO: temporarily, until the complete authorization story is implemented, we consider operations
        // allowed for user roles to be permitted unrestricted (even to unauthenticated users)
        if (Arrays.asList(rolesAllowed).contains(Role.USER)) {
            return;
        }

        if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
            requestContext.abortWith(
                    JSONResponse.createErrorResponse(Status.UNAUTHORIZED, "User is not authenticated"));
            return;
        }

        for (final String role : rolesAllowed) {
            if (requestContext.getSecurityContext().isUserInRole(role)) {
                return;
            }
        }
    }

    requestContext.abortWith(JSONResponse.createErrorResponse(Status.FORBIDDEN,
            "User is authenticated but doesn't have access to this resource"));
}
 
Example 4
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 5
Source File: RateLimitingFilter.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Transactional
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    SecurityContext securityContext = requestContext.getSecurityContext();
    String username = securityContext.getUserPrincipal().getName();

    User user = entityManager.createQuery("SELECT u FROM User u WHERE u.username=:username", User.class).setParameter(
            "username", username).getSingleResult();

    if (user.getAmountOfApiCalls() >= user.getMaxApiCallsPerMinute()) {
        requestContext.abortWith(Response.status(Response.Status.TOO_MANY_REQUESTS).build());
    }

    user.setAmountOfApiCalls(user.getAmountOfApiCalls() + 1);
    System.out.println(user);
}
 
Example 6
Source File: AuthDynamicFeature.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
  final SecurityContext sc = requestContext.getSecurityContext();
  if (!isUserLoggedIn(sc)) {
    try {
      final String destResource =
          URLEncoder.encode(requestContext.getUriInfo().getRequestUri().getPath(), "UTF-8");
      final URI loginURI = requestContext.getUriInfo().getBaseUriBuilder()
          .path(WebServerConstants.MAIN_LOGIN_RESOURCE_NAME)
          .queryParam(WebServerConstants.REDIRECT_QUERY_PARM, destResource)
          .build();
      requestContext.abortWith(Response.temporaryRedirect(loginURI).build()
      );
    } catch (final Exception ex) {
      final String errMsg = String.format("Failed to forward the request to login page: %s", ex.getMessage());
      logger.error(errMsg, ex);
      requestContext.abortWith(
          Response.serverError()
              .entity(errMsg)
              .build());
    }
  }
}
 
Example 7
Source File: IllBehavedRequestFilterTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestCtx) throws IOException {
    // ContainerRequestFilter should replace the entity stream with a filtered one based on the original entity
    // stream (see AbstractFilterInterceptorTest for examples of well behaved filters).
    int read = requestCtx.getEntityStream().read();
    if (read != 'x') {
        // 402 so it's distinguishable from 400 and 500 that the server could respond
        requestCtx.abortWith(status(PAYMENT_REQUIRED).build());
    }
}
 
Example 8
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 9
Source File: CallbackFilter.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext request) {
	URI uri = URI.create(getClients().getCallbackUrl());
	if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) {
	    logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath());
		return;
	}
	
	Session session = getSession(request, true);
	JaxrsWebContext context = getContext(request, session);
	Client client = getClient(session);
	if (client == null) {
	    client = getClient(context);
	}
	if (client == null) {
		context.setResponseStatus(422);
		if (listener != null) {
		    listener.authFailed(session);
		}
	} else {
		try {
			Credentials credentials = client.getCredentials(context);
			UserProfile userProfile = client.getUserProfile(credentials, context);
			session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName());
			session.addAttribute(PRINCIPAL, userProfile);
			if (listener != null) {
                listener.authSuccess(session, userProfile);
			}
			getConfiguration().getSessionStore().save(session);
			context.setResponseStatus(Response.Status.OK.getStatusCode());
		} catch (RequiresHttpAction e) {
			context.setResponseStatus(e.getCode());
			if (listener != null) {
                listener.authFailed(session);
            }
		}
	}
	request.abortWith(context.getResponse());
}
 
Example 10
Source File: HostFilter.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (resourceInfo != null) {
        if (resourceInfo.getResourceMethod().getAnnotation(NoIPRestriction.class) == null) {
            requestContext.abortWith(Response.serverError().build());
        }
        if (!remoteHostMatcher.isAllowed(request)) {
            requestContext.abortWith(Response.serverError().build());
        }
    }

}
 
Example 11
Source File: TrellisHttpFilter.java    From trellis with Apache License 2.0 5 votes vote down vote up
private void validateVersion(final ContainerRequestContext ctx) {
    final String version = ctx.getUriInfo().getQueryParameters().getFirst("version");
    if (version != null) {
        // Check well-formedness
        if (Version.valueOf(version) == null) {
            ctx.abortWith(status(BAD_REQUEST).build());
        // Do not allow mutating versioned resources
        } else if (mutatingMethods.contains(ctx.getMethod())) {
            ctx.abortWith(status(METHOD_NOT_ALLOWED).build());
        }
    }
}
 
Example 12
Source File: RequestAssertionConsumerFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean processParams(ContainerRequestContext ct,
                             MultivaluedMap<String, String> params,
                             boolean postBinding) {
    String encodedSamlResponse = params.getFirst(SSOConstants.SAML_RESPONSE);
    String relayState = params.getFirst(SSOConstants.RELAY_STATE);
    if (relayState == null && encodedSamlResponse == null) {
        // initial redirect to IDP has not happened yet, let the SAML authentication filter do it
        JAXRSUtils.getCurrentMessage().put(SSOConstants.RACS_IS_COLLOCATED, Boolean.TRUE);
        return false;
    }
    ct.abortWith(doProcessSamlResponse(encodedSamlResponse, relayState, postBinding));
    return true;
}
 
Example 13
Source File: CORSFilter.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    // Browser does pre-flight CORS checks
    // If it's a preflight request, we abort the request with
    // a 200 status, and the CORS headers are added in the
    // response filter method below.
    if (isPreflightRequest(requestContext)) {
        requestContext.abortWith(Response.ok().build());
    }
}
 
Example 14
Source File: SamlPostBindingFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();
    if (checkSecurityContext(m)) {
        return;
    }
    try {
        SamlRequestInfo info = createSamlRequestInfo(m);
        info.setIdpServiceAddress(getIdpServiceAddress());
        // This depends on RequestDispatcherProvider linking
        // SamlRequestInfo with the jsp page which will fill
        // in the XHTML form using SamlRequestInfo
        // in principle we could've built the XHTML form right here
        // but it will be cleaner to get that done in JSP

        String contextCookie = createCookie(SSOConstants.RELAY_STATE,
                                            info.getRelayState(),
                                            info.getWebAppContext(),
                                            info.getWebAppDomain());
        new MessageContextImpl(m).getHttpServletResponse().addHeader(
            HttpHeaders.SET_COOKIE, contextCookie);

        context.abortWith(Response.ok(info)
                       .type("text/html")
                       .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store")
                       .header("Pragma", "no-cache")
                       .build());

    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example 15
Source File: BookServer.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (requestContext.getUriInfo().getPath().endsWith("/blockAndThrowException")) {
        requestContext.setProperty("blocked", Boolean.TRUE);
        requestContext.abortWith(Response.ok().build());
    }
}
 
Example 16
Source File: RestSecurityInterceptor.java    From opensoc-streaming with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	
	// get our token...		
	Map<String, Cookie> cookies = requestContext.getCookies();
	
	Cookie authTokenCookie = cookies.get( "authToken" );
	if( authTokenCookie == null )
	{
		requestContext.abortWith(ACCESS_DENIED );
		return;			
	}
	
	String authToken = authTokenCookie.getValue();
	try {
		
		if( ! AuthToken.validateToken(configProps, authToken) )
		{
			requestContext.abortWith(ACCESS_DENIED );
			return;	
		}
	} 
	catch (Exception e) {

		e.printStackTrace();
		requestContext.abortWith(ACCESS_DENIED );
		return;
	}

	// if the token is good, just return...
	
}
 
Example 17
Source File: ServerStatusRequestFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
  if (!serverHealthMonitor.get().isHealthy()) {
    requestContext.abortWith(Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(
      serverHealthMonitor.get().getStatus()).build());
  }
}
 
Example 18
Source File: MigrationFilter.java    From ameba with MIT License 4 votes vote down vote up
private void migrateView(ContainerRequestContext req) {
    req.abortWith(Response.fromResponse(
            resource.migrateView(MigrationFeature.getMigrationId())
    ).status(500).build());
}
 
Example 19
Source File: FormWebUiAuthenticationFilter.java    From presto with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext request)
{
    String path = request.getUriInfo().getRequestUri().getPath();
    if (isPublicUiResource(path)) {
        return;
    }

    // authenticator over a secure connection bypasses the form login
    if (authenticator.isPresent() && request.getSecurityContext().isSecure()) {
        handleProtocolLoginRequest(authenticator.get(), request);
        return;
    }

    // login and logout resource is not visible to protocol authenticators
    if ((path.equals(UI_LOGIN) && request.getMethod().equals("POST")) || path.equals(UI_LOGOUT)) {
        return;
    }

    // check if the user is already authenticated
    Optional<String> username = getAuthenticatedUsername(request);
    if (username.isPresent()) {
        // if the authenticated user is requesting the login page, send them directly to the ui
        if (path.equals(LOGIN_FORM)) {
            request.abortWith(redirectFromSuccessfulLoginResponse(request.getUriInfo().getRequestUri().getQuery()).build());
            return;
        }
        setAuthenticatedIdentity(request, username.get());
        return;
    }

    // send 401 to REST api calls and redirect to others
    if (path.startsWith("/ui/api/")) {
        sendWwwAuthenticate(request, "Unauthorized", ImmutableSet.of("Presto-Form-Login"));
        return;
    }

    if (!isAuthenticationEnabled(request.getSecurityContext().isSecure())) {
        request.abortWith(Response.seeOther(DISABLED_LOCATION_URI).build());
        return;
    }

    if (path.equals(LOGIN_FORM)) {
        return;
    }

    // redirect to login page
    request.abortWith(Response.seeOther(LOGIN_FORM_URI).build());

    request.abortWith(Response.seeOther(buildLoginFormURI(request.getUriInfo())).build());
}
 
Example 20
Source File: SecurityFilter.java    From divide with Apache License 2.0 4 votes vote down vote up
private UserContext abort(ContainerRequestContext request, String message) {
    log.warning("Auth Failed: " + message);
    request.abortWith(notAuthReponse(message));
    return null;
}