Java Code Examples for io.vertx.ext.auth.User#isAuthorized()

The following examples show how to use io.vertx.ext.auth.User#isAuthorized() . 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: ClientVerticle.java    From VX-API-Gateway with 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 2
Source File: AuthenticationUtils.java    From besu with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static boolean isPermitted(
    final Optional<AuthenticationService> authenticationService,
    final Optional<User> optionalUser,
    final JsonRpcMethod jsonRpcMethod) {

  AtomicBoolean foundMatchingPermission = new AtomicBoolean();

  if (authenticationService.isEmpty()) {
    // no auth provider configured thus anything is permitted
    return true;
  }

  if (optionalUser.isPresent()) {
    User user = optionalUser.get();
    for (String perm : jsonRpcMethod.getPermissions()) {
      user.isAuthorized(
          perm,
          (authed) -> {
            if (authed.result()) {
              LOG.trace(
                  "user {} authorized : {} via permission {}",
                  user,
                  jsonRpcMethod.getName(),
                  perm);
              foundMatchingPermission.set(true);
            }
          });
      // exit if a matching permission was found, no need to keep checking
      if (foundMatchingPermission.get()) {
        return foundMatchingPermission.get();
      }
    }
  }

  if (!foundMatchingPermission.get()) {
    LOG.trace("user NOT authorized : {}", jsonRpcMethod.getName());
  }
  return foundMatchingPermission.get();
}
 
Example 3
Source File: ClientVerticle.java    From VX-API-Gateway with 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 4
Source File: ClientVerticle.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 进入创建API
 * 
 * @param rct
 */
public void staticAPI(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 5
Source File: ClientVerticle.java    From VX-API-Gateway with 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 6
Source File: ClientVerticle.java    From VX-API-Gateway with 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 7
Source File: ClientVerticle.java    From VX-API-Gateway with 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 8
Source File: ClientVerticle.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 添加一个API
 * 
 * @param rct
 */
public void addAPI(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}] 执行添加API...", rct.session().<String>get("userName")));
				JsonObject bodyAsJson = rct.getBodyAsJson();
				VxApisDTO dto = VxApisDTO.fromJson(bodyAsJson);
				dto.setApiCreateTime(Instant.now());
				JsonObject param = new JsonObject();
				param.put("apiName", dto.getApiName());
				param.put("appName", dto.getAppName());
				param.put("api", dto.toJson());
				vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.ADD_API, param, cres -> {
					if (cres.succeeded()) {
						response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, cres.result().body()));
						LOG.info(MessageFormat.format("[user : {0}] 执行添加API-->结果: {1}", rct.session().<String>get("userName"), cres.result().body()));
					} else {
						LOG.error(MessageFormat.format("[user : {0}] 执行添加API-->失败:{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}] 执行添加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 9
Source File: ClientVerticle.java    From VX-API-Gateway with 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 10
Source File: CheckAuthorityProcessor.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public void preHandle(RoutingContext context) {
  User user = context.user();
  if (user == null) {
    context.fail(401);
    return;
  }
  user.isAuthorized(annotation.authority(), result -> {
    if (!result.result()) {
      context.fail(403);
    } else {
      context.next();
    }
  });
}
 
Example 11
Source File: AuthHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void authorize(User user, Handler<AsyncResult<Void>> handler) {
  int requiredcount = authorities.size();
  if (requiredcount > 0) {
    if (user == null) {
      handler.handle(Future.failedFuture(FORBIDDEN));
      return;
    }

    AtomicInteger count = new AtomicInteger();
    AtomicBoolean sentFailure = new AtomicBoolean();

    Handler<AsyncResult<Boolean>> authHandler = res -> {
      if (res.succeeded()) {
        if (res.result()) {
          if (count.incrementAndGet() == requiredcount) {
            // Has all required authorities
            handler.handle(Future.succeededFuture());
          }
        } else {
          if (sentFailure.compareAndSet(false, true)) {
            handler.handle(Future.failedFuture(FORBIDDEN));
          }
        }
      } else {
        handler.handle(Future.failedFuture(res.cause()));
      }
    };
    for (String authority : authorities) {
      if (!sentFailure.get()) {
        user.isAuthorized(authority, authHandler);
      }
    }
  } else {
    // No auth required
    handler.handle(Future.succeededFuture());
  }
}
 
Example 12
Source File: AuthShiroExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example5(User user) {

    user.isAuthorized("newsletter:edit:13", res -> {
      if (res.succeeded()) {
        boolean hasPermission = res.result();
      } else {
        // Failed to
      }
    });

  }
 
Example 13
Source File: AuthShiroExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example6(User user) {

    user.isAuthorized("role:manager", res -> {
      if (res.succeeded()) {
        boolean hasRole = res.result();
      } else {
        // Failed to
      }
    });

  }
 
Example 14
Source File: ClientVerticle.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
/**
 * 删除一个API
 * 
 * @param rct
 */
public void delAPI(RoutingContext rct) {
	String apiName = rct.request().getParam("apiName");
	String appName = rct.request().getParam("appName");
	HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8);
	if (StrUtil.isNullOrEmpty(appName, apiName)) {
		response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C1400));
	} else {

		User user = rct.user();
		user.isAuthorized(VxApiRolesConstant.WRITE, res -> {

			if (res.succeeded()) {
				JsonObject body = new JsonObject();
				body.put("apiName", apiName);
				body.put("appName", appName);
				if (res.result()) {
					LOG.info(MessageFormat.format("[user : {0}] 执行删除API:{1}...", rct.session().<String>get("userName"), apiName));
					vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.DEL_API, body, 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(), apiName));
							if (vertx.isClustered()) {
								vertx.eventBus().publish(VxApiEventBusAddressConstant.DEPLOY_API_STOP, body.copy().put("thisVertxName", thisVertxName));
								LOG.info("广播告诉集群环境中暂停应用:" + appName + "的" + apiName + "API");
							}
						} else {
							LOG.error(MessageFormat.format("[user : {0}] 执行删除API:{2}-->失败:{1}", rct.session().get("userName"), cres.cause(), apiName));
							response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, cres.cause().toString()));
						}
					});
				} else {
					LOG.error(MessageFormat.format("[user : {0}] 执行删除API:{1}-->失败:未授权或者无权限", rct.session().get("userName"), apiName));
					response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401));
				}
			} else {
				LOG.error(MessageFormat.format("[user : {0}] 执行删除API:{2}-->失败:{1}", rct.session().get("userName"), res.cause(), apiName));
				response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage()));
			}
		});
	}

}