io.vertx.ext.auth.authorization.Authorization Java Examples

The following examples show how to use io.vertx.ext.auth.authorization.Authorization. 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: SqlAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
private void getPermissions(String username, Handler<AsyncResult<Set<Authorization>>> resultHandler) {
  if (options.getPermissionsQuery() != null) {
    client.preparedQuery(options.getPermissionsQuery()).execute(Tuple.of(username), preparedQuery -> {
      if (preparedQuery.succeeded()) {
        RowSet<Row> rows = preparedQuery.result();
        Set<Authorization> authorizations = new HashSet<>();
        for (Row row : rows) {
          String permission = row.getString(0);
          authorizations.add(PermissionBasedAuthorization.create(permission));
        }
        resultHandler.handle(Future.succeededFuture(authorizations));
      } else {
        resultHandler.handle(Future.failedFuture(preparedQuery.cause()));
      }
    });
  } else {
    resultHandler.handle(Future.succeededFuture(Collections.emptySet()));
  }
}
 
Example #2
Source File: RouteToEBServiceHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private User fakeUser(String username) {
  return new User() {
    @Override public JsonObject attributes() {
      return null;
    }
    @Override public User isAuthorized(Authorization authority, Handler<AsyncResult<java.lang.Boolean>> resultHandler) {
      return null;
    }
    @Override public User isAuthorized(String s, Handler<AsyncResult<Boolean>> handler) {
      return null;
    }
    @Override public User clearCache() {
      return null;
    }
    @Override public JsonObject principal() {
      return new JsonObject().put("username", username);
    }
    @Override public void setAuthProvider(AuthProvider authProvider) { }
  };
}
 
Example #3
Source File: RoleBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  User user = context.user();
  if (user != null) {
    Authorization resolvedAuthorization = getResolvedAuthorization(context);
    for (String providerId: user.authorizations().getProviderIds()) {
      for (Authorization authorization : user.authorizations().get(providerId)) {
        if (authorization.verify(resolvedAuthorization)) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #4
Source File: WildcardPermissionBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(Authorization otherAuthorization) {
  if (otherAuthorization instanceof WildcardPermissionBasedAuthorizationImpl) {
    WildcardPermissionBasedAuthorizationImpl otherWildcardPermission = (WildcardPermissionBasedAuthorizationImpl) otherAuthorization;
    if (wildcardPermission.implies((otherWildcardPermission).wildcardPermission)) {
      if (getResource() == null) {
        return true;
      }
      return getResource().equals(otherWildcardPermission.getResource());
    }
  }
  else if (otherAuthorization instanceof PermissionBasedAuthorization) {
    PermissionBasedAuthorization otherPermission = (PermissionBasedAuthorization) otherAuthorization;
    if (this.permission.equals(otherPermission.getPermission())) {
      if (getResource() == null) {
        return true;
      }
      return getResource().equals(otherPermission.getResource());
    }
  }
  return false;
}
 
Example #5
Source File: WildcardPermissionBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  User user = context.user();
  if (user != null) {
    Authorization resolvedAuthorization = getResolvedAuthorization(context);
    for (String providerId: user.authorizations().getProviderIds()) {
      for (Authorization authorization : user.authorizations().get(providerId)) {
        if (authorization.verify(resolvedAuthorization)) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #6
Source File: ScopeAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public void getAuthorizations(User user, Handler<AsyncResult<Void>> handler) {
  String scopes = user.principal().getString("scope");

  final Set<Authorization> authorizations = new HashSet<>();

  // avoid the case when scope is the literal "null" value.
  if (scopes != null) {
    String sep = user.attributes().getString("scope_separator", scopeSeparator);
    for (String scope : scopes.split(Pattern.quote(sep))) {
      authorizations.add(PermissionBasedAuthorization.create(scope));
    }
  }
  user.authorizations().add(getId(), authorizations);
  // return
  handler.handle(Future.succeededFuture());
}
 
Example #7
Source File: KeycloakAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
private static void extractApplicationRoles(JsonObject accessToken, Set<Authorization> authorizations) {
  JsonObject resourceAccess = accessToken
    .getJsonObject("resource_access", EMPTY_JSON);

  for (String resource : resourceAccess.fieldNames()) {
    JsonArray appRoles = resourceAccess
      // locate the right resource
      .getJsonObject(resource, EMPTY_JSON)
      // locate the role list
      .getJsonArray("roles");

    if (appRoles != null && appRoles.size() >= 0) {
      for (Object el : appRoles) {
        // convert to the authorization type
        authorizations.add(
          RoleBasedAuthorization
            .create((String) el)
            // fix it to the right resource
            .setResource(resource));
      }
    }
  }
}
 
Example #8
Source File: PropertyFileAuthenticationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public void getAuthorizations(io.vertx.ext.auth.User user, Handler<AsyncResult<Void>> resultHandler) {
  String username = user.principal().getString("username");
  getUser(username, userResult -> {
    if (userResult.succeeded()) {
      Set<Authorization> result = new HashSet<>();
      for (Role role : userResult.result().roles.values()) {
        result.add(RoleBasedAuthorization.create(role.name));
        for (String permission : role.permissions) {
          result.add(WildcardPermissionBasedAuthorization.create(permission));
        }
      }
      user.authorizations().add(getId(), result);
      resultHandler.handle(Future.succeededFuture());
    } else {
      resultHandler.handle(Future.failedFuture("invalid username"));
    }
  });
}
 
Example #9
Source File: SqlAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public void getAuthorizations(User user, Handler<AsyncResult<Void>> resultHandler) {
  String username = user.principal().getString("username");
  if (username != null) {
    getRoles(username, roleResponse -> {
      if (roleResponse.succeeded()) {
        Set<Authorization> authorizations = new HashSet<>(roleResponse.result());
        getPermissions(username, permissionResponse -> {
          if (permissionResponse.succeeded()) {
            authorizations.addAll(permissionResponse.result());
            user.authorizations().add(getId(), authorizations);
            resultHandler.handle(Future.succeededFuture());
          } else {
            resultHandler.handle(Future.failedFuture(permissionResponse.cause()));
          }
        });
      } else {
        resultHandler.handle(Future.failedFuture(roleResponse.cause()));
      }
    });
  } else {
    resultHandler.handle(Future.failedFuture("Couldn't get the username from the principal"));
  }
}
 
Example #10
Source File: SqlAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
private void getRoles(String username, Handler<AsyncResult<Set<Authorization>>> resultHandler) {
  if (options.getRolesQuery() != null) {
    client.preparedQuery(options.getRolesQuery()).execute(Tuple.of(username), preparedQuery -> {
      if (preparedQuery.succeeded()) {
        RowSet<Row> rows = preparedQuery.result();
        Set<Authorization> authorizations = new HashSet<>();
        for (Row row : rows) {
          String role = row.getString(0);
          authorizations.add(RoleBasedAuthorization.create(role));
        }
        resultHandler.handle(Future.succeededFuture(authorizations));
      } else {
        resultHandler.handle(Future.failedFuture(preparedQuery.cause()));
      }
    });
  } else {
    resultHandler.handle(Future.succeededFuture(Collections.emptySet()));
  }
}
 
Example #11
Source File: AuthorizationConverter.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
public static Authorization decode(JsonObject json) throws IllegalArgumentException {
  Objects.requireNonNull(json);

  Authorization result = AndAuthorizationConverter.decode(json);
  if (result == null) {
    result = NotAuthorizationConverter.decode(json);
    if (result == null) {
      result = OrAuthorizationConverter.decode(json);
      if (result == null) {
        result = PermissionBasedAuthorizationConverter.decode(json);
        if (result == null) {
          result = RoleBasedAuthorizationConverter.decode(json);
          if (result == null) {
            result = WildcardPermissionBasedAuthorizationConverter.decode(json);
          }
        }
      }
    }
  }
  return result;
}
 
Example #12
Source File: AuthorizationConverter.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
public static JsonObject encode(Authorization value) throws IllegalArgumentException {
  Objects.requireNonNull(value);

  // decide which JsonCodec we should use
  if (value instanceof AndAuthorization) {
    return AndAuthorizationConverter.encode((AndAuthorization) value);
  } else if (value instanceof NotAuthorization) {
    return NotAuthorizationConverter.encode((NotAuthorization) value);
  } else if (value instanceof OrAuthorization) {
    return OrAuthorizationConverter.encode((OrAuthorization) value);
  } else if (value instanceof PermissionBasedAuthorization) {
    return PermissionBasedAuthorizationConverter.encode((PermissionBasedAuthorization) value);
  } else if (value instanceof RoleBasedAuthorization) {
    return RoleBasedAuthorizationConverter.encode((RoleBasedAuthorization) value);
  } else if (value instanceof WildcardPermissionBasedAuthorization) {
    return WildcardPermissionBasedAuthorizationConverter.encode((WildcardPermissionBasedAuthorization) value);
  } else {
    throw new IllegalArgumentException("Unsupported authorization " + value.getClass());
  }
}
 
Example #13
Source File: UserConverter.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
public static JsonObject encode(User value) throws IllegalArgumentException {
  Objects.requireNonNull(value);

  JsonObject json = new JsonObject();
  json.put(FIELD_PRINCIPAL, value.principal());
  JsonObject jsonAuthorizations = new JsonObject();
  for (String providerId: value.authorizations().getProviderIds()) {
    JsonArray jsonAuthorizationByProvider = new JsonArray();
    jsonAuthorizations.put(providerId, jsonAuthorizationByProvider);
    for (Authorization authorization : value.authorizations().get(providerId)) {
      jsonAuthorizationByProvider.add(AuthorizationConverter.encode(authorization));
    }
  }
  json.put(FIELD_AUTHORIZATIONS, jsonAuthorizations);
  return json;
}
 
Example #14
Source File: MultiAuthorizationHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private AuthorizationProvider createProvider(String id, Authorization authorization) {
  Set<Authorization> _authorizations = new HashSet<>();
  _authorizations.add(authorization);
  return new AuthorizationProvider() {

    @Override
    public String getId() {
      return id;
    }

    @Override
    public void getAuthorizations(User user, Handler<AsyncResult<Void>> handler) {
      user.authorizations().add(getId(), _authorizations);
      handler.handle(Future.succeededFuture());
    }
  };
}
 
Example #15
Source File: PermissionBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  User user = context.user();
  if (user != null) {
    Authorization resolvedAuthorization = getResolvedAuthorization(context);
    for (String providerId: user.authorizations().getProviderIds()) {
      for (Authorization authorization : user.authorizations().get(providerId)) {
        if (authorization.verify(resolvedAuthorization)) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #16
Source File: PermissionBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(Authorization otherAuthorization) {
  Objects.requireNonNull(otherAuthorization);

  if (otherAuthorization instanceof PermissionBasedAuthorization) {
    PermissionBasedAuthorization otherPermissionBasedAuthorization = (PermissionBasedAuthorization) otherAuthorization;
    if (permission.equals(otherPermissionBasedAuthorization.getPermission())) {
      if (getResource() == null) {
        return otherPermissionBasedAuthorization.getResource() == null;
      }
      return getResource().equals(otherPermissionBasedAuthorization.getResource());
    }
  }
  else if (otherAuthorization instanceof WildcardPermissionBasedAuthorization) {
    WildcardPermissionBasedAuthorization otherWildcardPermissionBasedAuthorization = (WildcardPermissionBasedAuthorization) otherAuthorization;
    if (permission.equals(otherWildcardPermissionBasedAuthorization.getPermission())) {
      if (getResource() == null) {
        return otherWildcardPermissionBasedAuthorization.getResource() == null;
      }
      return getResource().equals(otherWildcardPermissionBasedAuthorization.getResource());
    }
  }
  return false;
}
 
Example #17
Source File: OrAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  for (Authorization authorization : authorizations) {
    if (authorization.match(context)) {
      return true;
    }
  }
  return false;
}
 
Example #18
Source File: AndAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  for (Authorization authorization : authorizations) {
    if (!authorization.match(context)) {
      return false;
    }
  }
  return true;
}
 
Example #19
Source File: OrAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(Authorization otherAuthorization) {
  Objects.requireNonNull(otherAuthorization);

  if (otherAuthorization instanceof OrAuthorization) {
    return this.equals(otherAuthorization);
  } else if (authorizations.size() == 1) {
    return authorizations.get(0).verify(otherAuthorization);
  }
  return false;
}
 
Example #20
Source File: AuthorizationsImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public Authorizations add(String providerId, Authorization authorization) {
  Objects.requireNonNull(providerId);
  Objects.requireNonNull(authorization);

  getOrCreateAuthorizations(providerId).add(authorization);
  return this;
}
 
Example #21
Source File: AuthorizationsImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public Authorizations add(String providerId, Set<Authorization> authorizations) {
  Objects.requireNonNull(providerId);
  Objects.requireNonNull(authorizations);

  getOrCreateAuthorizations(providerId).addAll(authorizations);
  return this;
}
 
Example #22
Source File: RoleBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(Authorization otherAuthorization) {
  Objects.requireNonNull(otherAuthorization);

  if (otherAuthorization instanceof RoleBasedAuthorization) {
    RoleBasedAuthorization otherRoleBasedAuthorization = (RoleBasedAuthorization) otherAuthorization;
    if (role.equals(otherRoleBasedAuthorization.getRole())) {
      if (getResource() == null) {
        return otherRoleBasedAuthorization.getResource() == null;
      }
      return getResource().equals(otherRoleBasedAuthorization.getResource());
    }
  }
  return false;
}
 
Example #23
Source File: AndAuthorizationConverter.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public static JsonObject encode(AndAuthorization value) throws IllegalArgumentException {
  Objects.requireNonNull(value);

  JsonObject result = new JsonObject();
  result.put(FIELD_TYPE, TYPE_AND_AUTHORIZATION);
  JsonArray authorizations = new JsonArray();
  result.put(FIELD_AUTHORIZATIONS, authorizations);
  for (Authorization authorization : value.getAuthorizations()) {
    authorizations.add(AuthorizationConverter.encode(authorization));
  }
  return result;
}
 
Example #24
Source File: OrAuthorizationConverter.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public static JsonObject encode(OrAuthorization value) throws IllegalArgumentException {
  Objects.requireNonNull(value);

  JsonObject result = new JsonObject();
  result.put(FIELD_TYPE, TYPE_AND_AUTHORIZATION);
  JsonArray authorizations = new JsonArray();
  result.put(FIELD_AUTHORIZATIONS, authorizations);
  for (Authorization authorization : value.getAuthorizations()) {
    authorizations.add(AuthorizationConverter.encode(authorization));
  }
  return result;
}
 
Example #25
Source File: KeycloakAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
private static void extractRealmRoles(JsonObject accessToken, Set<Authorization> authorizations) {
  JsonArray appRoles = accessToken
    .getJsonObject("realm_access", EMPTY_JSON)
    // locate the role list
    .getJsonArray("roles");

  if (appRoles != null && appRoles.size() >= 0) {
    for (Object el : appRoles) {
      // convert to the authorization type
      authorizations.add(RoleBasedAuthorization.create((String) el));
    }
  }
}
 
Example #26
Source File: JDBCAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public void getAuthorizations(User user, Handler<AsyncResult<Void>> resultHandler) {
  client.getConnection(connectionResponse -> {
    if (connectionResponse.succeeded()) {
      String username = user.principal().getString(usernameKey);
      if (username != null) {
        JsonArray params = new JsonArray().add(username);
        SQLConnection connection = connectionResponse.result();
        getRoles(connection, params, roleResponse -> {
          if (roleResponse.succeeded()) {
            Set<Authorization> authorizations = new HashSet<>(roleResponse.result());
            getPermissions(connection, params, permissionResponse -> {
              if (permissionResponse.succeeded()) {
                authorizations.addAll(permissionResponse.result());
                user.authorizations().add(getId(), authorizations);
                resultHandler.handle(Future.succeededFuture());
              } else {
                resultHandler.handle(Future.failedFuture(permissionResponse.cause()));
              }
              connection.close();
            });
          } else {
            resultHandler.handle(Future.failedFuture(roleResponse.cause()));
            connection.close();
          }
        });
      } else {
        resultHandler.handle(Future.failedFuture("Couldn't get the username"));
        connectionResponse.result().close();
      }
    } else {
      resultHandler.handle(Future.failedFuture(connectionResponse.cause()));
    }
  });
}
 
Example #27
Source File: MongoUserUtilTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void createUserAndPermissionsTest() throws Throwable {
  MongoClient mongoClient = this.getMongoClient();
  MongoAuthentication authnProvider = MongoAuthentication.create(mongoClient, new MongoAuthenticationOptions());
  MongoAuthorization authzProvider = MongoAuthorization.create("abc", mongoClient, new MongoAuthorizationOptions());
  MongoUserUtil userUtil = MongoUserUtil.create(mongoClient);
  List<String> roles = Arrays.asList("a", "b");
  List<String> perms = Arrays.asList("c", "d");
  JsonObject credentials = new JsonObject()
    .put("username", "fizz")
    .put("password", "buzz");
  userUtil
    .createUser("fizz", "buzz")
    .flatMap(id -> userUtil.createUserRolesAndPermissions("fizz", roles, perms))
    .flatMap(id -> authnProvider.authenticate(credentials))
    .flatMap(user -> authzProvider.getAuthorizations(user).map(v -> user))
    .onFailure(this::fail)
    .onSuccess(user -> {
      Set<Authorization> auths = user.authorizations().get("abc");
      assertTrue(auths.contains(RoleBasedAuthorization.create("a")));
      assertTrue(auths.contains(RoleBasedAuthorization.create("b")));
      assertFalse(auths.contains(RoleBasedAuthorization.create("c")));
      assertTrue(auths.contains(PermissionBasedAuthorization.create("c")));
      assertTrue(auths.contains(PermissionBasedAuthorization.create("d")));
      assertFalse(auths.contains(PermissionBasedAuthorization.create("e")));
      this.complete();
    });
  await();
}
 
Example #28
Source File: ServiceAuthInterceptor.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Add a single authority to the authorities set.
 *
 * @param authorization authority
 * @return self
 */
public ServiceAuthInterceptor addAuthorization(Authorization authorization) {
  if (authorizations == null) {
    authorizations = new HashSet<>();
  }
  authorizations.add(authorization);
  return this;
}
 
Example #29
Source File: AuthHandlerTestBase.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
protected void testAuthorization(String username, boolean fail, Authorization authority) throws Exception {
  if (requiresSession()) {
    router.route().handler(BodyHandler.create());
    SessionStore store = getSessionStore();
    router.route().handler(SessionHandler.create(store));
  }
  AuthenticationProvider authNProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties");
  AuthorizationProvider authZProvider = PropertyFileAuthorization.create(vertx, "login/loginusers.properties");

  AuthenticationHandler authNHandler = createAuthHandler(authNProvider);
  router.route().handler(rc -> {
    // we need to be logged in
    if (rc.user() == null) {
      JsonObject authInfo = new JsonObject().put("username", username).put("password", "delicious:sausages");
      authNProvider.authenticate(authInfo, res -> {
        if (res.succeeded()) {
          rc.setUser(res.result());
          rc.next();
        } else {
          rc.fail(res.cause());
        }
      });
    }
  });
  router.route().handler(authNHandler);
  if (authority != null) {
    router.route().handler(AuthorizationHandler.create(authority).addAuthorizationProvider(authZProvider));
  }
  router.route().handler(rc -> rc.response().end());

  testRequest(HttpMethod.GET, "/", fail ? 403: 200, fail? "Forbidden": "OK");
}
 
Example #30
Source File: UserImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public User isAuthorized(Authorization authorization, Handler<AsyncResult<Boolean>> resultHandler) {
  Objects.requireNonNull(authorization);
  Objects.requireNonNull(resultHandler);

  AuthorizationContext context = new AuthorizationContextImpl(this);
  resultHandler.handle(Future.succeededFuture(authorization.match(context)));
  return this;
}