io.vertx.ext.web.handler.impl.HttpStatusException Java Examples
The following examples show how to use
io.vertx.ext.web.handler.impl.HttpStatusException.
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: AdminLoginHandler.java From joyqueue with Apache License 2.0 | 6 votes |
@Override public void handle(final RoutingContext context) { HttpServerRequest request = context.request(); Session session = context.session(); if (session == null) { context.fail(new HttpStatusException(HTTP_INTERNAL_ERROR, "No session - did you forget to include a SessionHandler?")); return; } String remoteIP = getRemoteIP(request); context.put(REMOTE_IP, remoteIP); User user = session.get(userSessionKey); if (user == null) { user = userService.findByCode(DEFAULT_LOGIN_USER_CODE); } //存放用户上下文信息 context.put(USER_KEY, user); context.next(); }
Example #2
Source File: CustomAuthHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Test public void testCredentialsValidationErrorPropagation() throws Exception { Handler<RoutingContext> handler = rc -> { fail("should not get here"); rc.response().end("Welcome to the protected resource!"); }; Throwable rootCause = new IllegalArgumentException("validation of credentials failed"); AuthenticationProvider authProvider = mock(AuthenticationProvider.class); doAnswer(invocation -> { final Handler<AsyncResult<User>> resultHandler = invocation.getArgument(1); resultHandler.handle(Future.failedFuture(rootCause)); return null; }).when(authProvider).authenticate(any(Credentials.class), any(Handler.class)); router.route("/protected/*").handler(newAuthHandler(authProvider, exception -> { assertTrue(exception instanceof HttpStatusException); assertEquals(rootCause, exception.getCause()); })); router.route("/protected/somepage").handler(handler); testRequest(HttpMethod.GET, "/protected/somepage", 401, "Unauthorized"); }
Example #3
Source File: RoutingContextImpl.java From vertx-web with Apache License 2.0 | 6 votes |
private MultiMap getQueryParams() { // Check if query params are already parsed if (queryParams == null) { try { queryParams = MultiMap.caseInsensitiveMultiMap(); // Decode query parameters and put inside context.queryParams Map<String, List<String>> decodedParams = new QueryStringDecoder(request.uri()).parameters(); for (Map.Entry<String, List<String>> entry : decodedParams.entrySet()) queryParams.add(entry.getKey(), entry.getValue()); } catch (IllegalArgumentException e) { throw new HttpStatusException(400, "Error while decoding query params", e); } } return queryParams; }
Example #4
Source File: RoutingContextImplBase.java From vertx-web with Apache License 2.0 | 6 votes |
protected void unhandledFailure(int statusCode, Throwable failure, RouterImpl router) { int code = statusCode != -1 ? statusCode : (failure instanceof HttpStatusException) ? ((HttpStatusException) failure).getStatusCode() : 500; Handler<RoutingContext> errorHandler = router.getErrorHandlerByStatusCode(code); if (errorHandler != null) { try { errorHandler.handle(this); } catch (Throwable t) { LOG.error("Error in error handler", t); } } if (!response().ended() && !response().closed()) { try { response().setStatusCode(code); } catch (IllegalArgumentException e) { // means that there are invalid chars in the status message response() .setStatusMessage(HttpResponseStatus.valueOf(code).reasonPhrase()) .setStatusCode(code); } response().end(response().getStatusMessage()); } }
Example #5
Source File: SSOSessionHandler.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Override public void handle(RoutingContext context) { // if no user in context, continue if (context.user() == null) { context.next(); return; } authorizeUser(context, h -> { if (h.failed()) { Throwable cause = h.cause(); LOGGER.debug("An error occurs while checking SSO Session upon the current user : {}", context.user().principal(), cause); if (cause instanceof AccountDisabledException) { // user has been disabled, invalidate session context.clearUser(); context.session().destroy(); } else if (cause instanceof InvalidRequestException) { context.fail(new HttpStatusException(403, "Invalid request for the current SSO context")); return; } } context.next(); }); }
Example #6
Source File: RedirectAuthHandlerImpl.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) { Session session = context.session(); if (session != null) { try { // Save current request in session - we'll get redirected back here after successful login io.vertx.reactivex.core.http.HttpServerRequest request = new io.vertx.reactivex.core.http.HttpServerRequest(context.request()); Map<String, String> requestParameters = request.params().entries().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); session.put(returnURLParam, UriBuilderRequest.resolveProxyRequest(request, request.path(), requestParameters)); // Now redirect to the login url String uri = UriBuilderRequest.resolveProxyRequest(request, loginRedirectURL, requestParameters, true); handler.handle(Future.failedFuture(new HttpStatusException(302, uri))); } catch (Exception e) { logger.warn("Failed to decode login redirect url", e); handler.handle(Future.failedFuture(new HttpStatusException(302, loginRedirectURL))); } } else { handler.handle(Future.failedFuture("No session - did you forget to include a SessionHandler?")); } }
Example #7
Source File: RouterFactorySecurityTest.java From vertx-web with Apache License 2.0 | 5 votes |
private AuthenticationHandler mockFailingAuthHandler(Handler<RoutingContext> mockHandler) { return new AuthenticationHandlerImpl<AuthenticationProvider>((authInfo, resultHandler) -> resultHandler.handle(Future.succeededFuture(User.create(new JsonObject())))) { @Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) { mockHandler.handle(context); handler.handle(Future.failedFuture(new HttpStatusException(401))); } }; }
Example #8
Source File: JWTURIHandler.java From xyz-hub with Apache License 2.0 | 5 votes |
@Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) { final List<String> access_token = Query.queryParam(Query.ACCESS_TOKEN, context); if (access_token != null && access_token.size() > 0) { handler.handle(Future.succeededFuture(new JsonObject().put("jwt", access_token.get(0)).put("options", options))); return; } handler.handle(Future.failedFuture(new HttpStatusException(UNAUTHORIZED.code(), "Missing auth credentials."))); }
Example #9
Source File: CustomAuthHandlerTest.java From vertx-web with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void testHttpStatusExceptionFailurePropagation() throws Exception { Handler<RoutingContext> handler = rc -> { fail("should not get here"); rc.response().end("Welcome to the protected resource!"); }; Throwable rootCause = new HttpStatusException(499, "bla"); AuthenticationProvider authProvider = mock(AuthenticationProvider.class); doAnswer(invocation -> { final Handler<AsyncResult<User>> resultHandler = invocation.getArgument(1); resultHandler.handle(Future.failedFuture(rootCause)); return null; }).when(authProvider).authenticate(any(Credentials.class), any(Handler.class)); router.route("/protected/*").handler(newAuthHandler(authProvider, exception -> { assertTrue(exception instanceof HttpStatusException); assertEquals(rootCause, exception); })); router.route("/protected/somepage").handler(handler); router.errorHandler(499, rc -> rc .response() .setStatusCode(((HttpStatusException)rc.failure()).getStatusCode()) .setStatusMessage(((HttpStatusException)rc.failure()).getPayload()) .end() ); testRequest(HttpMethod.GET, "/protected/somepage", 499, "bla"); }
Example #10
Source File: ApiCodegenExamples.java From vertx-web with Apache License 2.0 | 5 votes |
public void implGetTransactionsListFailure(String from, String to, ServiceRequest context, Handler<AsyncResult<ServiceResponse>> resultHandler) { // Return a failed result resultHandler.handle( Future.failedFuture( new HttpStatusException(555, "Something bad happened") ) ); }
Example #11
Source File: OAuth2AuthHandlerImpl.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private void processException(RoutingContext context, Throwable exception) { int statusCode = -1; if (exception instanceof HttpStatusException) { statusCode = ((HttpStatusException) exception).getStatusCode(); } else if (exception instanceof OAuth2Exception) { statusCode = ((OAuth2Exception) exception).getHttpStatusCode(); } if (statusCode == 401) { context.response().putHeader("WWW-Authenticate", authenticateHeader()); } context.fail(exception); }
Example #12
Source File: OAuth2AuthHandlerImpl.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private void parseAuthorization(RoutingContext context, Handler<AsyncResult<String>> handler) { final HttpServerRequest request = context.request(); final String authorization = request.headers().get(io.vertx.core.http.HttpHeaders.AUTHORIZATION); String authToken = null; try { if (authorization != null) { // authorization header has been found check the value int idx = authorization.indexOf(' '); if (idx <= 0) { handler.handle(Future.failedFuture(new InvalidRequestException("The access token must be sent using the Authorization header field"))); return; } if (!BEARER.equalsIgnoreCase(authorization.substring(0, idx))) { handler.handle(Future.failedFuture(new HttpStatusException(401))); return; } authToken = authorization.substring(idx + 1); } else { // if no authorization header found, check authorization in body authToken = request.getParam(ACCESS_TOKEN); } if (authToken == null) { handler.handle(Future.failedFuture(new HttpStatusException(401))); return; } handler.handle(Future.succeededFuture(authToken)); } catch (RuntimeException e) { handler.handle(Future.failedFuture(e)); } }
Example #13
Source File: ErrorHandler.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Override public void handle(RoutingContext routingContext) { if (routingContext.failed()) { Throwable throwable = routingContext.failure(); // management exception (resource not found, server error, ...) if (throwable instanceof AbstractManagementException) { AbstractManagementException technicalManagementException = (AbstractManagementException) throwable; handleException(routingContext, technicalManagementException.getHttpStatusCode(), technicalManagementException.getMessage()); // oauth2 exception (token invalid exception) } else if (throwable instanceof OAuth2Exception) { OAuth2Exception oAuth2Exception = (OAuth2Exception) throwable; handleException(routingContext, oAuth2Exception.getHttpStatusCode(), oAuth2Exception.getMessage()); } else if (throwable instanceof PolicyChainException) { PolicyChainException policyChainException = (PolicyChainException) throwable; handleException(routingContext, policyChainException.statusCode(), policyChainException.key() + " : " + policyChainException.getMessage()); } else if (throwable instanceof HttpStatusException) { HttpStatusException httpStatusException = (HttpStatusException) throwable; handleException(routingContext, httpStatusException.getStatusCode(), httpStatusException.getPayload()); } else { logger.error(throwable.getMessage(), throwable); if (routingContext.statusCode() != -1) { routingContext .response() .setStatusCode(routingContext.statusCode()) .end(); } else { routingContext .response() .setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500) .end(); } } } }
Example #14
Source File: ErrorHandler.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Override public void handle(RoutingContext routingContext) { if (routingContext.failed()) { Throwable throwable = routingContext.failure(); // management exception (resource not found, server error, ...) if (throwable instanceof AbstractManagementException) { AbstractManagementException technicalManagementException = (AbstractManagementException) throwable; handleException(routingContext, "technical_error", technicalManagementException.getMessage()); // oauth2 exception (token invalid exception) } else if (throwable instanceof OAuth2Exception) { OAuth2Exception oAuth2Exception = (OAuth2Exception) throwable; handleException(routingContext, oAuth2Exception.getOAuth2ErrorCode(), oAuth2Exception.getMessage()); } else if (throwable instanceof PolicyChainException) { PolicyChainException policyChainException = (PolicyChainException) throwable; handleException(routingContext, policyChainException.key(), policyChainException.getMessage()); } else if (throwable instanceof HttpStatusException) { HttpStatusException httpStatusException = (HttpStatusException) throwable; handleException(routingContext, httpStatusException.getMessage(), httpStatusException.getPayload()); } else { logger.error("An exception occurs while handling incoming request", throwable); if (routingContext.statusCode() != -1) { routingContext .response() .setStatusCode(routingContext.statusCode()) .end(); } else { routingContext .response() .setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500) .end(); } } } }
Example #15
Source File: ErrorHandler.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Override public void handle(RoutingContext routingContext) { if (routingContext.failed()) { Throwable throwable = routingContext.failure(); // management exception (resource not found, server error, ...) if (throwable instanceof AbstractManagementException) { AbstractManagementException technicalManagementException = (AbstractManagementException) throwable; handleException(routingContext, technicalManagementException.getHttpStatusCode(), technicalManagementException.getMessage(), null); // oauth2 exception (token invalid exception) } else if (throwable instanceof OAuth2Exception) { OAuth2Exception oAuth2Exception = (OAuth2Exception) throwable; handleException(routingContext, oAuth2Exception.getHttpStatusCode(), oAuth2Exception.getMessage(), null); } else if (throwable instanceof SCIMException) { SCIMException scimException = (SCIMException) throwable; handleException(routingContext, scimException.getHttpStatusCode(), scimException.getMessage(), scimException.getScimType()); } else if (throwable instanceof HttpStatusException) { if (401 == ((HttpStatusException) throwable).getStatusCode()) { UnauthorizedException unauthorizedException = new UnauthorizedException(); handleException(routingContext, unauthorizedException.getHttpStatusCode(), unauthorizedException.getMessage(), null); } } else if (throwable instanceof PolicyChainException) { PolicyChainException policyChainException = (PolicyChainException) throwable; handleException(routingContext, policyChainException.statusCode(), policyChainException.key() + " : " + policyChainException.getMessage(), null); } else { logger.error(throwable.getMessage(), throwable); if (routingContext.statusCode() != -1) { routingContext .response() .setStatusCode(routingContext.statusCode()) .end(); } else { routingContext .response() .setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500) .end(); } } } }
Example #16
Source File: AuthorizationRequestFailureHandler.java From graviteeio-access-management with Apache License 2.0 | 4 votes |
@Override public void handle(RoutingContext routingContext) { if (routingContext.failed()) { try { AuthorizationRequest request = resolveInitialAuthorizeRequest(routingContext); Client client = routingContext.get(CLIENT_CONTEXT_KEY); String defaultErrorURL = UriBuilderRequest.resolveProxyRequest(routingContext.request(), defaultErrorPath, null); Throwable throwable = routingContext.failure(); if (throwable instanceof OAuth2Exception) { OAuth2Exception oAuth2Exception = (OAuth2Exception) throwable; // Manage exception processOAuth2Exception(request, oAuth2Exception, client, defaultErrorURL, h -> { if (h.failed()) { logger.error("An errors has occurred while handling authorization error response", h.cause()); routingContext.response().setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end(); return; } // redirect user to the error page with error code and description doRedirect(routingContext.response(), h.result()); }); } else if (throwable instanceof HttpStatusException) { // in case of http status exception, go to the default error page request.setRedirectUri(defaultErrorURL); HttpStatusException httpStatusException = (HttpStatusException) throwable; doRedirect(routingContext.response(), buildRedirectUri(httpStatusException.getMessage(), httpStatusException.getPayload(), request)); } else { logger.error("An exception has occurred while handling authorization request", throwable); if (routingContext.statusCode() != -1) { routingContext .response() .setStatusCode(routingContext.statusCode()) .end(); } else { routingContext .response() .setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500) .end(); } } } catch (Exception e) { logger.error("Unable to handle authorization error response", e); doRedirect(routingContext.response(), defaultErrorPath); } finally { // clean session cleanSession(routingContext); } } }
Example #17
Source File: AuthHandlerTools.java From hono with Eclipse Public License 2.0 | 4 votes |
/** * Processes an exception that occurred while trying to authenticate * a device. * <p> * This method checks if the given exception is an {@code HttpStatusException} * and if so, tries to extract the root cause of the problem from its * <em>cause</em> field. If the root cause is a {@link ServiceInvocationException} * then its error code is used to fail the routing context, otherwise the status * code from the {@code HttpStatusException} is used. In all other cases, the * context is failed with a 500 error code. * * @param ctx The routing context. * @param exception The cause of failure to process the request. * @param authenticateHeader The value to return in the HTTP Authenticate header. */ public static void processException( final RoutingContext ctx, final Throwable exception, final String authenticateHeader) { if (exception instanceof HttpStatusException) { final Throwable failure = Optional.ofNullable(exception.getCause()).map(c -> { if (c instanceof ServiceInvocationException) { // extract and use root cause return c; } else { return exception; } }).orElse(exception); final int statusCode; final String payload; if (failure instanceof ServiceInvocationException) { final ServiceInvocationException sie = (ServiceInvocationException) exception.getCause(); statusCode = sie.getErrorCode(); payload = null; } else { statusCode = ((HttpStatusException) exception).getStatusCode(); payload = ((HttpStatusException) exception).getPayload(); } switch (statusCode) { case 302: ctx.response() .putHeader(HttpHeaders.LOCATION, payload) .setStatusCode(302) .end("Redirecting to " + payload + "."); return; case 401: if (authenticateHeader != null) { ctx.response() .putHeader("WWW-Authenticate", authenticateHeader); } ctx.fail(failure); return; default: ctx.fail(failure); return; } } // fallback 500 ctx.fail(exception); }
Example #18
Source File: HttpStatusExceptionSupplier.java From joyqueue with Apache License 2.0 | 4 votes |
@Override public Class<? extends Throwable> type() { return HttpStatusException.class; }
Example #19
Source File: ChainAuthMixHandlerTest.java From vertx-web with Apache License 2.0 | 4 votes |
@Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) { handler.handle(Future.failedFuture(new HttpStatusException(401))); }
Example #20
Source File: HttpStatusExceptionSupplier.java From joyqueue with Apache License 2.0 | 4 votes |
@Override public Response error(final Throwable throwable) { HttpStatusException exception = (HttpStatusException) throwable; return Responses.error(RuntimeError.getCode(), exception.getStatusCode(), exception.getPayload()); }