Java Code Examples for io.vertx.ext.web.RoutingContext#user()

The following examples show how to use io.vertx.ext.web.RoutingContext#user() . These examples are extracted from open source projects. 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 Project: quarkus   File: QuarkusHttpUser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current user from the routing context. This method may block if proactive authentication is disabled,
 * as it may need to perform a potentially blocking operation.
 * If an IPM is provided this method will return the anonymous
 * identity if there is no active user, otherwise it will return null if there is no user.
 */
public static SecurityIdentity getSecurityIdentityBlocking(RoutingContext routingContext,
        IdentityProviderManager identityProviderManager) {
    QuarkusHttpUser existing = (QuarkusHttpUser) routingContext.user();
    if (existing != null) {
        return existing.getSecurityIdentity();
    }
    Uni<SecurityIdentity> deferred = routingContext.get(DEFERRED_IDENTITY_KEY);
    if (deferred != null) {
        return deferred.await().indefinitely();
    }
    if (identityProviderManager != null) {
        return identityProviderManager.authenticate(AnonymousAuthenticationRequest.INSTANCE).await().indefinitely();
    }
    return null;
}
 
Example 2
void handleOptionsRoute(final RoutingContext ctx) {

        final Span currentSpan = TracingHelper.buildServerChildSpan(
                tracer,
                TracingHandler.serverSpanContext(ctx),
                "process OPTIONS request",
                getClass().getSimpleName())
                .start();

        if (ctx.user() instanceof Device) {
            // Some providers use OPTIONS request to check if request works. Therefore returning 200.
            handle200(ctx);
        } else {
            handleUnsupportedUserType(ctx, currentSpan);
        }
        currentSpan.finish();
    }
 
Example 3
private void authUaaHandler(RoutingContext context) {
  if (context.user() != null) {
    JsonObject principal = context.user().principal();
    String username = null;  // TODO: Only for demo. Complete this in next version.
    // String username = KeycloakHelper.preferredUsername(principal);
    if (username == null) {
      context.response()
        .putHeader("content-type", "application/json")
        .end(new Account().setId("TEST666").setUsername("Eric").toString()); // TODO: no username should be an error
    } else {
      Future<AccountService> future = Future.future();
      EventBusService.getProxy(discovery, AccountService.class, future.completer());
      future.compose(accountService -> {
        Future<Account> accountFuture = Future.future();
        accountService.retrieveByUsername(username, accountFuture.completer());
        return accountFuture.map(a -> {
          ServiceDiscovery.releaseServiceObject(discovery, accountService);
          return a;
        });
      })
        .setHandler(resultHandlerNonEmpty(context)); // if user does not exist, should return 404
    }
  } else {
    context.fail(401);
  }
}
 
Example 4
Source Project: VX-API-Gateway   File: ClientVerticle.java    License: MIT License 6 votes vote down vote up
/**
 * 权限认证
 * 
 * @param rct
 */
public void staticAuth(RoutingContext rct) {
	User user = rct.user();
	if (user == null) {
		rct.response().end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401));
	} else {
		user.isAuthorized(VxApiRolesConstant.READ, res -> {
			if (res.succeeded()) {
				if (res.result()) {
					rct.next();
				} else {
					rct.response().end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401));
				}
			} else {
				rct.response().end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage()));
			}
		});
	}
}
 
Example 5
Source Project: nubes   File: CheckTokenHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  User user = context.user();
  if (user != null) {
      authorize(user, event -> {});
    return;
  }
  String apiToken;
  try {
    apiToken = parseApiToken(context.request());
  } catch (BadRequestException bre) {
    context.fail(bre);
    return;
  }
  if (apiToken == null) {
    context.fail(401);
    return;
  }
  doAuth(context, apiToken);
}
 
Example 6
Source Project: xyz-hub   File: Api.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the log marker for the request.
 *
 * @return the marker or null, if no marker was found.
 */
public static JWTPayload getJWT(RoutingContext context) {
  if (context == null) {
    return null;
  }
  JWTPayload payload = context.get(JWT);
  if (payload == null && context.user() != null) {
    payload = Json.mapper.convertValue(context.user().principal(), JWTPayload.class);
    context.put(JWT, payload);
  }

  return payload;
}
 
Example 7
void handlePostTelemetry(final RoutingContext ctx) {

        if (Device.class.isInstance(ctx.user())) {
            final Device device = (Device) ctx.user();
            uploadTelemetryMessage(ctx, device.getTenantId(), device.getDeviceId());
        } else {
            handle401(ctx);
        }
    }
 
Example 8
Source Project: quarkus   File: RemoteUserAttribute.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String readAttribute(final RoutingContext exchange) {
    QuarkusHttpUser sc = (QuarkusHttpUser) exchange.user();
    if (sc == null) {
        return null;
    }
    return sc.getSecurityIdentity().getPrincipal().getName();
}
 
Example 9
Source Project: VX-API-Gateway   File: ClientVerticle.java    License: MIT License 5 votes vote down vote up
/**
 * 进入创建Application
 * 
 * @param rct
 */
public void staticAPP(RoutingContext rct) {
	User user = rct.user();
	user.isAuthorized(VxApiRolesConstant.WRITE, res -> {
		if (res.succeeded()) {
			if (res.result()) {
				rct.next();
			} else {
				rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_HTML_UTF8).end(UNAUTHORIZED_RESULT);
			}
		} else {
			rct.response().end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage()));
		}
	});
}
 
Example 10
Source Project: VX-API-Gateway   File: ClientVerticle.java    License: MIT License 5 votes vote down vote up
/**
 * 添加应用
 * 
 * @param rct
 */
public void addAPP(RoutingContext rct) {
	User user = rct.user();
	HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8);
	user.isAuthorized(VxApiRolesConstant.WRITE, res -> {
		if (res.succeeded()) {
			if (res.result()) {
				LOG.info(MessageFormat.format("[user : {0}] 执行添加应用...", rct.session().<String>get("userName")));
				VxApiApplicationDTO dto = VxApiApplicationDTO.fromJson(rct.getBodyAsJson());
				JsonObject param = new JsonObject();
				param.put("appName", dto.getAppName());
				param.put("app", dto.toJson().put("time", Instant.now()));
				vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.ADD_APP, param, cres -> {
					if (cres.succeeded()) {
						response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, cres.result().body()));
						LOG.info(MessageFormat.format("[user : {0}] 执行添加应用-->结果: {1}", rct.session().<String>get("userName"), cres.result().body()));
					} else {
						LOG.error(MessageFormat.format("[user : {0}] 执行添加应用-->失败:{1}", rct.session().get("userName"), cres.cause()));

						if (cres.cause().toString().contains("UNIQUE")) {
							response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C1444, cres.cause().toString()));
						} else {
							response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, cres.cause().toString()));
						}
					}
				});
			} else {
				LOG.error(MessageFormat.format("[user : {0}] 执行添加应用-->失败:未授权或者无权利", rct.session().get("userName")));
				response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401));
			}
		} else {
			LOG.error(MessageFormat.format("[user : {0}] 执行添加应用-->失败:{1}", rct.session().get("userName"), res.cause()));
			response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage()));
		}
	});
}
 
Example 11
Source Project: VX-API-Gateway   File: ClientVerticle.java    License: MIT License 5 votes vote down vote up
/**
 * 修改一个应用
 * 
 * @param rct
 */
public void updtAPP(RoutingContext rct) {
	User user = rct.user();
	HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8);
	user.isAuthorized(VxApiRolesConstant.WRITE, res -> {
		if (res.succeeded()) {
			if (res.result()) {
				LOG.info(MessageFormat.format("[user : {0}] 执行修改应用...", rct.session().<String>get("userName")));
				VxApiApplicationDTO dto = VxApiApplicationDTO.fromJson(rct.getBodyAsJson());
				JsonObject param = new JsonObject();
				param.put("appName", dto.getAppName());
				param.put("app", dto.toJson());
				vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.UPDT_APP, param, cres -> {
					if (cres.succeeded()) {
						response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, cres.result().body()));
						LOG.info(MessageFormat.format("[user : {0}] 执行修改应用:{2}-->结果: {1}", rct.session().<String>get("userName"),
								cres.result().body(), dto.getAppName()));
					} else {
						LOG.error(MessageFormat.format("[user : {0}] 执行修改应用-->失败:{1}", rct.session().get("userName"), cres.cause()));
						response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, cres.cause().toString()));
					}
				});
			} else {
				LOG.error(MessageFormat.format("[user : {0}] 执行修改应用-->失败:未授权或者无权利", rct.session().get("userName")));
				response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401));
			}
		} else {
			LOG.error(MessageFormat.format("[user : {0}] 执行修改应用-->失败:{1}", rct.session().get("userName"), res.cause()));
			response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage()));
		}
	});
}
 
Example 12
Source Project: VX-API-Gateway   File: ClientVerticle.java    License: MIT License 5 votes vote down vote up
/**
 * 删除应用程序
 * 
 * @param rct
 */
public void delAPP(RoutingContext rct) {
	String name = rct.request().getParam("name");
	HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8);
	if (StrUtil.isNullOrEmpty(name)) {
		response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C1404));
	} else {
		User user = rct.user();
		user.isAuthorized(VxApiRolesConstant.WRITE, res -> {
			if (res.succeeded()) {
				JsonObject config = new JsonObject().put("appName", name);
				vertx.eventBus().send(thisVertxName + VxApiEventBusAddressConstant.DEPLOY_APP_UNDEPLOY, config);
				if (res.result()) {
					// 将应用暂停
					if (vertx.isClustered()) {
						vertx.eventBus().publish(VxApiEventBusAddressConstant.DEPLOY_APP_UNDEPLOY, config.copy().put("thisVertxName", thisVertxName));
						LOG.info("执行删除应用-->广播告诉集群环境中暂停应用:" + name);
					}
					LOG.info(MessageFormat.format("[user : {0}] 执行删除应用{1}...", rct.session().<String>get("userName"), name));
					vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.DEL_APP, name, cres -> {
						if (cres.succeeded()) {
							response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, cres.result().body()));
							LOG.info(MessageFormat.format("[user : {0}] 执行删除应用:{2}-->结果: {1}", rct.session().<String>get("userName"),
									cres.result().body(), name));
						} else {
							LOG.error(MessageFormat.format("[user : {0}] 执行删除应用:{2}-->失败:{1}", rct.session().get("userName"), cres.cause(), name));
							response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, cres.cause().toString()));
						}
					});
				} else {
					LOG.error(MessageFormat.format("[user : {0}] 执行删除应用:{1}-->失败:未授权或者无权限", rct.session().get("userName"), name));
					response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401));
				}
			} else {
				LOG.error(MessageFormat.format("[user : {0}] 执行删除应用:{2}-->失败:{1}", rct.session().get("userName"), res.cause(), name));
				response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage()));
			}
		});
	}
}
 
Example 13
void handlePostEvent(final RoutingContext ctx) {

        if (Device.class.isInstance(ctx.user())) {
            final Device device = (Device) ctx.user();
            uploadEventMessage(ctx, device.getTenantId(), device.getDeviceId());
        } else {
            handle401(ctx);
        }
    }
 
Example 14
Source Project: VX-API-Gateway   File: ClientVerticle.java    License: MIT License 5 votes vote down vote up
/**
 * 更新一个API
 * 
 * @param rct
 */
public void updtAPI(RoutingContext rct) {
	User user = rct.user();
	HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8);
	user.isAuthorized(VxApiRolesConstant.WRITE, res -> {
		if (res.succeeded()) {
			if (res.result()) {
				LOG.info(MessageFormat.format("[user : {0}] 执行修改应用...", rct.session().<String>get("userName")));
				VxApisDTO dto = VxApisDTO.fromJson(rct.getBodyAsJson());
				if (dto.getApiCreateTime() == null) {
					dto.setApiCreateTime(Instant.now());
				}
				JsonObject param = new JsonObject();
				param.put("apiName", dto.getApiName());
				param.put("api", dto.toJson());
				vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.UPDT_API, param, cres -> {
					if (cres.succeeded()) {
						response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, cres.result().body()));
						LOG.info(MessageFormat.format("[user : {0}] 执行修改API:{2}-->结果: {1}", rct.session().<String>get("userName"),
								cres.result().body(), dto.getApiName()));
					} else {
						LOG.error(MessageFormat.format("[user : {0}] 执行修改API-->失败:{1}", rct.session().get("userName"), cres.cause()));
						response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, cres.cause().toString()));
					}
				});
			} else {
				LOG.error(MessageFormat.format("[user : {0}] 执行修改API-->失败:未授权或者无权利", rct.session().get("userName")));
				response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401));
			}
		} else {
			LOG.error(MessageFormat.format("[user : {0}] 执行修改API-->失败:{1}", rct.session().get("userName"), res.cause()));
			response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage()));
		}
	});
}
 
Example 15
Source Project: vertx-web   File: WebAuthnHandlerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {

  if (response == null) {
    LOG.error("No callback mounted!");
    ctx.fail(500);
    return;
  }

  if (matchesRoute(ctx, response)) {
    if (LOG.isWarnEnabled()) {
      LOG.warn("The callback route is shaded by the WebAuthNAuthHandler, ensure the callback route is added BEFORE the WebAuthNAuthHandler route!");
    }
    ctx.fail(500);
    return;
  }

  if (matchesRoute(ctx, register)) {
    if (LOG.isWarnEnabled()) {
      LOG.warn("The register callback route is shaded by the WebAuthNAuthHandler, ensure the callback route is added BEFORE the WebAuthNAuthHandler route!");
    }
    ctx.fail(500);
    return;
  }

  if (matchesRoute(ctx, login)) {
    if (LOG.isWarnEnabled()) {
      LOG.warn("The login callback route is shaded by the WebAuthNAuthHandler, ensure the callback route is added BEFORE the WebAuthNAuthHandler route!");
    }
    ctx.fail(500);
    return;
  }

  if (ctx.user() == null) {
    ctx.fail(401);
  } else {
    ctx.next();
  }
}
 
Example 16
Source Project: VX-API-Gateway   File: ClientVerticle.java    License: MIT License 5 votes vote down vote up
/**
 * 退出登录
 * 
 * @param rct
 */
public void loginOut(RoutingContext rct) {
	if (rct.user() != null) {
		rct.user().clearCache();
	}
	rct.session().remove(VxApiClientStaticAuth.AUTHORIZATION);
	rct.session().put(VxApiClientStaticAuth.IS_AUTH, "false");
	rct.response().putHeader("Location", "/").setStatusCode(302).end();
}
 
Example 17
private void dataHandler(final RoutingContext ctx, final UploadHandler uploadHandler) {

        if (!(ctx.user() instanceof Device)) {
            LOG.warn("Not a device");
            return;
        }

        final Device gatewayDevice = (Device) ctx.user();

        final String deviceTenant = gatewayDevice.getTenantId();
        final String requestTenant = ctx.pathParam(SIGFOX_PARAM_TENANT);

        final String deviceId = ctx.queryParams().get(SIGFOX_PARAM_DEVICE_ID);
        final String strData = ctx.queryParams().get(SIGFOX_PARAM_DATA);
        final Buffer data = decodeData(strData);

        LOG.debug("{} handler - deviceTenant: {}, requestTenant: {}, deviceId: {}, data: {}",
                ctx.request().method(), deviceTenant, requestTenant, deviceId, strData);

        if ( requestTenant == null ) {
            ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "missing the tenant information in the request URL"));
            return;
        }

        if (!requestTenant.equals(deviceTenant)) {
            ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "tenant information mismatch"));
            return;
        }

        final String contentType = (data != null) ? CONTENT_TYPE_OCTET_STREAM
                : EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION;

        uploadHandler.upload(ctx, deviceTenant, deviceId, data, contentType);
    }
 
Example 18
Source Project: nubes   File: LogoutProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void postHandle(RoutingContext context) {
  User user = context.user();
  if (user != null) {
    user.clearCache();
    context.clearUser();
  }
  context.next();
}
 
Example 19
Source Project: quarkus   File: VertxRequestHandler.java    License: Apache License 2.0 4 votes vote down vote up
private void dispatch(RoutingContext routingContext, InputStream is, VertxOutput output) {
    ManagedContext requestContext = beanContainer.requestContext();
    requestContext.activate();
    routingContext.remove(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
    QuarkusHttpUser user = (QuarkusHttpUser) routingContext.user();
    if (association != null) {
        association.setIdentity(QuarkusHttpUser.getSecurityIdentity(routingContext, null));
    }
    currentVertxRequest.setCurrent(routingContext);
    try {
        Context ctx = vertx.getOrCreateContext();
        HttpServerRequest request = routingContext.request();
        ResteasyUriInfo uriInfo = VertxUtil.extractUriInfo(request, rootPath);
        ResteasyHttpHeaders headers = VertxUtil.extractHttpHeaders(request);
        HttpServerResponse response = request.response();
        VertxHttpResponse vertxResponse = new VertxHttpResponse(request, dispatcher.getProviderFactory(),
                request.method(), allocator, output);

        // using a supplier to make the remote Address resolution lazy: often it's not needed and it's not very cheap to create.
        LazyHostSupplier hostSupplier = new LazyHostSupplier(request);

        VertxHttpRequest vertxRequest = new VertxHttpRequest(ctx, routingContext, headers, uriInfo, request.rawMethod(),
                hostSupplier,
                dispatcher.getDispatcher(), vertxResponse, requestContext);
        vertxRequest.setInputStream(is);
        try {
            ResteasyContext.pushContext(SecurityContext.class, new QuarkusResteasySecurityContext(request, routingContext));
            ResteasyContext.pushContext(RoutingContext.class, routingContext);
            dispatcher.service(ctx, request, response, vertxRequest, vertxResponse, true);
        } catch (Failure e1) {
            vertxResponse.setStatus(e1.getErrorCode());
            if (e1.isLoggable()) {
                log.error(e1);
            }
        } catch (Throwable ex) {
            routingContext.fail(ex);
        }

        boolean suspended = vertxRequest.getAsyncContext().isSuspended();
        boolean requestContextActive = requestContext.isActive();
        if (!suspended) {
            try {
                if (requestContextActive) {
                    requestContext.terminate();
                }
            } finally {
                try {
                    vertxResponse.finish();
                } catch (IOException e) {
                    log.debug("IOException writing JAX-RS response", e);
                }
            }
        } else {
            //we need the request context to stick around
            requestContext.deactivate();
        }
    } catch (Throwable t) {
        try {
            routingContext.fail(t);
        } finally {
            if (requestContext.isActive()) {
                requestContext.terminate();
            }
        }
    }
}
 
Example 20
Source Project: quarkus   File: HttpAuthorizer.java    License: Apache License 2.0 4 votes vote down vote up
private void doPermissionCheck(RoutingContext routingContext,
        Uni<SecurityIdentity> identity, int index,
        SecurityIdentity augmentedIdentity,
        List<HttpSecurityPolicy> permissionCheckers) {
    if (index == permissionCheckers.size()) {
        QuarkusHttpUser currentUser = (QuarkusHttpUser) routingContext.user();
        if (augmentedIdentity != null) {
            if (!augmentedIdentity.isAnonymous()
                    && (currentUser == null || currentUser.getSecurityIdentity() != augmentedIdentity)) {
                routingContext.setUser(new QuarkusHttpUser(augmentedIdentity));
                routingContext.put(QuarkusHttpUser.DEFERRED_IDENTITY_KEY, Uni.createFrom().item(augmentedIdentity));
            }
        }
        routingContext.next();
        return;
    }
    //get the current checker
    HttpSecurityPolicy res = permissionCheckers.get(index);
    res.checkPermission(routingContext, identity, CONTEXT)
            .subscribe().with(new Consumer<HttpSecurityPolicy.CheckResult>() {
                @Override
                public void accept(HttpSecurityPolicy.CheckResult checkResult) {
                    if (!checkResult.isPermitted()) {
                        doDeny(identity, routingContext);
                    } else {
                        if (checkResult.getAugmentedIdentity() != null) {
                            doPermissionCheck(routingContext, Uni.createFrom().item(checkResult.getAugmentedIdentity()),
                                    index + 1, checkResult.getAugmentedIdentity(), permissionCheckers);
                        } else {
                            //attempt to run the next checker
                            doPermissionCheck(routingContext, identity, index + 1, augmentedIdentity, permissionCheckers);
                        }
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    routingContext.fail(throwable);
                }
            });
}