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

The following examples show how to use io.vertx.ext.auth.authorization.RoleBasedAuthorization. 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: MultiAuthorizationHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTAuthenticationWithAuthorization1() throws Exception {
  // we are testing the following:
  // authentication via jwt
  // no authorization provider is registered
  // an authorization is required on the path
  // => the test should fail
  router.route("/protected/*").handler(JWTAuthHandler.create(authProvider));
  router.route("/protected/*").handler(AuthorizationHandler.create(RoleBasedAuthorization.create("role1")));

  router.route("/protected/page1").handler(rc -> {
    assertNotNull(rc.user());
    assertEquals("paulo", rc.user().principal().getString("sub"));
    rc.response().end("Welcome");
  });

  // login with correct credentials
  testRequest(HttpMethod.GET, "/protected/page1",
      req -> req.putHeader("Authorization",
          "Bearer " + authProvider.generateToken(new JsonObject().put("sub", "paulo"), new JWTOptions())),
      403, "Forbidden", "Forbidden");
}
 
Example #2
Source File: MicroProfileTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void itShouldBeFalseForRoleUnknown(TestContext should) {

  final Async test = should.async();

  User user = User.create(new JsonObject(
      "{\n" +
        "      \"iss\": \"https://server.example.com\",\n" +
        "      \"aud\": \"s6BhdRkqt3\",\n" +
        "      \"jti\": \"a-123\",\n" +
        "      \"exp\": 999999999999,\n" +
        "      \"iat\": 1311280970,\n" +
        "      \"sub\": \"24400320\",\n" +
        "      \"upn\": \"[email protected]\",\n" +
        "      \"groups\": [\"red-group\", \"green-group\", \"admin-group\", \"admin\"]\n" +
        "}"));

  MicroProfileAuthorization.create().getAuthorizations(user, call -> {
    should.assertTrue(call.succeeded());
    should.assertFalse(user.authorizations().getProviderIds().isEmpty());
    should.assertFalse(RoleBasedAuthorization.create("unknown").match(user));
    test.complete();
  });
}
 
Example #3
Source File: RoleBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch2(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", RoleBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertFalse(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r2", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #4
Source File: RoleBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", RoleBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertTrue(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #5
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 #6
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 #7
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 #8
Source File: MySQLTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthoriseNotHasRole(TestContext should) {
  final Async test = should.async();

  JsonObject authInfo = new JsonObject();
  authInfo.put("username", "lopus").put("password", "secret");

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.succeeded());
    final User user = authenticate.result();
    should.assertNotNull(user);
    AuthorizationProvider authz = SqlAuthorization.create(mysql);
    authz.getAuthorizations(user, getAuthorizations -> {
      should.assertTrue(getAuthorizations.succeeded());
      // attest
      should.assertFalse(RoleBasedAuthorization.create("manager").match(user));
      test.complete();
    });
  });
}
 
Example #9
Source File: MySQLTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthoriseHasRole(TestContext should) {
  final Async test = should.async();

  JsonObject authInfo = new JsonObject();
  authInfo.put("username", "lopus").put("password", "secret");

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.succeeded());
    final User user = authenticate.result();
    should.assertNotNull(user);
    AuthorizationProvider authz = SqlAuthorization.create(mysql);
    authz.getAuthorizations(user, getAuthorizations -> {
      should.assertTrue(getAuthorizations.succeeded());
      // attest
      should.assertTrue(RoleBasedAuthorization.create("dev").match(user));
      test.complete();
    });
  });
}
 
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: WebExamples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void example40(AuthorizationProvider authProvider, Router router) {
  // Need "list_products" authorization to list products
  router.route("/listproducts/*").handler(
    // create the handler that will perform the attestation
    AuthorizationHandler.create(
      // what to attest
      PermissionBasedAuthorization.create("list_products"))
      // where to lookup the authorizations for the user
      .addAuthorizationProvider(authProvider));

  // Only "admin" has access to /private/settings
  router.route("/private/settings/*").handler(
    // create the handler that will perform the attestation
    AuthorizationHandler.create(
      // what to attest
      RoleBasedAuthorization.create("admin"))
      .addAuthorizationProvider(authProvider));
}
 
Example #12
Source File: MultiAuthorizationHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTAuthenticationWithAuthorization2() throws Exception {
  // we are testing the following:
  // authentication via jwt
  // one authorization provider is registered
  // an authorization is required on the path
  // => the test should succeed
  router.route("/protected/*").handler(JWTAuthHandler.create(authProvider));
  router.route("/protected/*")
      .handler(
          AuthorizationHandler.create(RoleBasedAuthorization.create("role1"))
          .addAuthorizationProvider(createProvider("authzProvider1", RoleBasedAuthorization.create("role1")))
      );

  router.route("/protected/page1").handler(rc -> {
    assertNotNull(rc.user());
    assertEquals("paulo", rc.user().principal().getString("sub"));
    rc.response().end("Welcome");
  });

  // login with correct credentials
  testRequest(HttpMethod.GET, "/protected/page1",
      req -> req.putHeader("Authorization",
          "Bearer " + authProvider.generateToken(new JsonObject().put("sub", "paulo"), new JWTOptions())),
      200, "OK", "Welcome");
}
 
Example #13
Source File: MongoAuthImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
private User createUser(JsonObject json) {
  User user = new UserImpl(json);
  json.put(PROPERTY_FIELD_SALT, getSaltField());
  json.put(PROPERTY_FIELD_PASSWORD, getPasswordField());
  JsonArray roles = json.getJsonArray(mongoAuthorizationOptions.getRoleField());
  if (roles!=null) {
    for (int i=0; i<roles.size(); i++) {
      String role = roles.getString(i);
      user.authorizations().add(PROVIDER_ID, RoleBasedAuthorization.create(role));
    }
  }
  JsonArray permissions = json.getJsonArray(mongoAuthorizationOptions.getPermissionField());
  if (permissions!=null) {
    for (int i=0; i<permissions.size(); i++) {
      String permission = permissions.getString(i);
      user.authorizations().add(PROVIDER_ID, PermissionBasedAuthorization.create(permission));
    }
  }
  user.setAuthProvider(this);
  return user;
}
 
Example #14
Source File: Examples.java    From vertx-service-proxy with Apache License 2.0 6 votes vote down vote up
public void secure(Vertx vertx) {
  // Create an instance of your service implementation
  SomeDatabaseService service = new SomeDatabaseServiceImpl();
  // Register the handler
  new ServiceBinder(vertx)
    .setAddress("database-service-address")
    // Secure the messages in transit
    .addInterceptor(
      new ServiceAuthInterceptor()
        // Tokens will be validated using JWT authentication
        .setAuthenticationProvider(JWTAuth.create(vertx, new JWTAuthOptions()))
        // optionally we can secure permissions too:

        // an admin
        .addAuthorization(RoleBasedAuthorization.create("admin"))
        // that can print
        .addAuthorization(PermissionBasedAuthorization.create("print"))

        // where the authorizations are loaded, let's assume from the token
        // but they could be loaded from a database or a file if needed
        .setAuthorizationProvider(
          JWTAuthorization.create("permissions")))

    .register(SomeDatabaseService.class, service);
}
 
Example #15
Source File: MongoAuthorizationTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthoriseNotHasRole() {
  JsonObject authInfo = new JsonObject();
  authInfo.put(authenticationOptions.getUsernameField(), "tim").put(authenticationOptions.getPasswordField(), "sausages");
  getAuthenticationProvider().authenticate(authInfo, onSuccess(user -> {
    assertNotNull(user);
    fillUserAuthorizations(user, onSuccess(has -> {
      assertFalse(RoleBasedAuthorization.create("manager").match(user));
      testComplete();
    }));
  }));
  await();
}
 
Example #16
Source File: MicroProfileTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void itShouldAssertThatTokenHasRoles(TestContext should) {

  final Async test = should.async();

  User user = User.create(new JsonObject(
      "{\n" +
        "      \"iss\": \"https://server.example.com\",\n" +
        "      \"aud\": \"s6BhdRkqt3\",\n" +
        "      \"jti\": \"a-123\",\n" +
        "      \"exp\": 999999999999,\n" +
        "      \"iat\": 1311280970,\n" +
        "      \"sub\": \"24400320\",\n" +
        "      \"upn\": \"[email protected]\",\n" +
        "      \"groups\": [\"red-group\", \"green-group\", \"admin-group\", \"admin\"]\n" +
        "}"));


  // assert that the user has the following roles:
  final List<String> roles = Arrays.asList("red-group", "green-group", "admin-group", "admin");

  MicroProfileAuthorization.create().getAuthorizations(user, call -> {
    should.assertTrue(call.succeeded());
    for (String role : roles) {
      should.assertTrue(RoleBasedAuthorization.create(role).match(user));
    }
    test.complete();
  });
}
 
Example #17
Source File: MicroProfileAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public void getAuthorizations(User user, Handler<AsyncResult<Void>> handler) {
  final String rootClaim = user.attributes().getString("rootClaim");
  final JsonObject accessToken =
    rootClaim == null ?
      user.principal() :
      user.attributes().getJsonObject(rootClaim);

  if (accessToken == null) {
    handler.handle(Future.failedFuture("User doesn't contain a decoded Token"));
    return;
  }

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

  // the spec MP-JWT 1.1 defines a custom grant called "groups"
  final JsonArray groups = accessToken.getJsonArray("groups");
  // This MP-JWT custom claim is the list of group names that have been assigned to the principal of the MP-JWT.
  // This typically will required a mapping at the application container level to application deployment roles,
  // but a a one-to-one between group names and application role names is required to be performed in addition
  // to any other mapping.

  if (groups != null && groups.size() >= 0) {
    for (Object el : groups) {
      // convert to the authorization type
      if (el instanceof String) {
        authorizations.add(RoleBasedAuthorization.create((String) el));
      } else {
        // abort the parsing
        handler.handle(Future.failedFuture("Cannot parse role: " + el));
        return;
      }
    }
  }

  user.authorizations().add(getId(), authorizations);
  // return
  handler.handle(Future.succeededFuture());
}
 
Example #18
Source File: MultiAuthorizationHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testJWTAuthenticationWithAuthorization3() throws Exception {
  // we are testing the following:
  // authentication via jwt
  // 3 authorization providers are registered
  // an authorization is required on the path
  // => the test should succeed
  router.route("/protected/*").handler(JWTAuthHandler.create(authProvider));
  router.route("/protected/*")
      .handler(
          AuthorizationHandler.create(RoleBasedAuthorization.create("role3"))
          .addAuthorizationProvider(createProvider("authzProvider1", RoleBasedAuthorization.create("role1")))
          .addAuthorizationProvider(createProvider("authzProvider2", RoleBasedAuthorization.create("role2")))
          .addAuthorizationProvider(createProvider("authzProvider3", RoleBasedAuthorization.create("role3")))
      );

  router.route("/protected/page1").handler(rc -> {
    assertNotNull(rc.user());
    assertEquals("paulo", rc.user().principal().getString("sub"));
    rc.response().end("Welcome");
  });

  // login with correct credentials
  testRequest(HttpMethod.GET, "/protected/page1",
      req -> req.putHeader("Authorization",
          "Bearer " + authProvider.generateToken(new JsonObject().put("sub", "paulo"), new JWTOptions())),
      200, "OK", "Welcome");
}
 
Example #19
Source File: RoleBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void testConverter() {
  TestUtils.testJsonCodec(RoleBasedAuthorization.create("role1"), RoleBasedAuthorizationConverter::encode,
    RoleBasedAuthorizationConverter::decode);
  TestUtils.testJsonCodec(RoleBasedAuthorization.create("role1").setResource("resource"),
    RoleBasedAuthorizationConverter::encode, RoleBasedAuthorizationConverter::decode);
}
 
Example #20
Source File: MultiAuthorizationHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testJWTAuthenticationWithAuthorization4() throws Exception {
  // we are testing the following:
  // authentication via jwt
  // 3 authorization providers are registered
  // an authorization is required on the path
  // => the test should fail since no authorization providers provide the correct authorization
  router.route("/protected/*").handler(JWTAuthHandler.create(authProvider));
  router.route("/protected/*")
      .handler(
          AuthorizationHandler.create(RoleBasedAuthorization.create("role4"))
          .addAuthorizationProvider(createProvider("authzProvider1", RoleBasedAuthorization.create("role1")))
          .addAuthorizationProvider(createProvider("authzProvider2", RoleBasedAuthorization.create("role2")))
          .addAuthorizationProvider(createProvider("authzProvider3", RoleBasedAuthorization.create("role3")))
      );

  router.route("/protected/page1").handler(rc -> {
    assertNotNull(rc.user());
    assertEquals("paulo", rc.user().principal().getString("sub"));
    rc.response().end("Welcome");
  });

  // login with correct credentials
  testRequest(HttpMethod.GET, "/protected/page1",
      req -> req.putHeader("Authorization",
          "Bearer " + authProvider.generateToken(new JsonObject().put("sub", "paulo"), new JWTOptions())),
      403, "Forbidden", "Forbidden");
}
 
Example #21
Source File: RoleBasedAuthorizationConverter.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public static RoleBasedAuthorization decode(JsonObject json) throws IllegalArgumentException {
  Objects.requireNonNull(json);

  if (TYPE_ROLE_BASED_AUTHORIZATION.equals(json.getString(FIELD_TYPE))) {
    RoleBasedAuthorization result = RoleBasedAuthorization.create(json.getString(FIELD_ROLE));
    if (json.getString(FIELD_RESOURCE) != null) {
      result.setResource(json.getString(FIELD_RESOURCE));
    }
    return result;

  }
  return null;
}
 
Example #22
Source File: RoleBasedAuthorizationConverter.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public static JsonObject encode(RoleBasedAuthorization value) throws IllegalArgumentException {
  Objects.requireNonNull(value);

  JsonObject result = new JsonObject();
  result.put(FIELD_TYPE, TYPE_ROLE_BASED_AUTHORIZATION);
  result.put(FIELD_ROLE, value.getRole());
  if (value.getResource() != null) {
    result.put(FIELD_RESOURCE, value.getResource());
  }
  return result;
}
 
Example #23
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 #24
Source File: AuthCommonExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example3(User user, AuthorizationProvider authorizationProvider) {
  // load the authorization for the given user:
  authorizationProvider.getAuthorizations(user, res -> {
    if (res.succeeded()) {
      // cache is populated, perform query
      if (RoleBasedAuthorization.create("admin").match(user)) {
        System.out.println("User has the authority");
      } else {
        System.out.println("User does not have the authority");
      }
    }
  });
}
 
Example #25
Source File: MongoAuthorizationTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthoriseHasRole() {
  JsonObject authInfo = new JsonObject();
  authInfo.put(authenticationOptions.getUsernameField(), "tim").put(authenticationOptions.getPasswordField(), "sausages");
  getAuthenticationProvider().authenticate(authInfo, onSuccess(user -> {
    assertNotNull(user);
    fillUserAuthorizations(user, onSuccess(has -> {
      assertTrue(RoleBasedAuthorization.create("developer").match(user));
      testComplete();
    }));
  }));
  await();
}
 
Example #26
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 #27
Source File: AuthSqlExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example8(User user, SqlAuthorization sqlAuthZ) {
  sqlAuthZ.getAuthorizations(user)
    .onSuccess(v -> {
      if (RoleBasedAuthorization.create("manager").match(user)) {
        // Has role!
      }
    });
}
 
Example #28
Source File: AuthOAuth2Examples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example13(Vertx vertx) {
  // you would get this config from the keycloak admin console
  JsonObject keycloakJson = new JsonObject()
    .put("realm", "master")
    .put("realm-public-key", "MIIBIjANBgkqhk...wIDAQAB")
    .put("auth-server-url", "http://localhost:9000/auth")
    .put("ssl-required", "external")
    .put("resource", "frontend")
    .put("credentials", new JsonObject()
      .put("secret", "2fbf5e18-b923-4a83-9657-b4ebd5317f60"));

  // Initialize the OAuth2 Library
  OAuth2Auth oauth2 = KeycloakAuth
    .create(vertx, OAuth2FlowType.PASSWORD, keycloakJson);

  // first get a token (authenticate)
  oauth2.authenticate(
    new JsonObject()
      .put("username", "user")
      .put("password", "secret"))
    .onSuccess(user -> {
      // now check for permissions
      AuthorizationProvider authz = KeycloakAuthorization.create();

      authz.getAuthorizations(user)
        .onSuccess(v -> {
          if (
            RoleBasedAuthorization.create("manage-account")
              .setResource("account")
              .match(user)) {
            // this user is authorized to manage its account
          }
        });
    });
}
 
Example #29
Source File: JDBCAuthorizationProviderTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthoriseNotHasRole() {
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("tim", "sausages");
  getAuthenticationProvider().authenticate(credentials, onSuccess(user -> {
    assertNotNull(user);
    fillUserAuthorizations(user, onSuccess(has -> {
      assertFalse(RoleBasedAuthorization.create("manager").match(user));
      testComplete();
    }));
  }));
  await();
}
 
Example #30
Source File: JDBCAuthorizationProviderTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthoriseHasRole() {
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("tim", "sausages");
  getAuthenticationProvider().authenticate(credentials, onSuccess(user -> {
    assertNotNull(user);
    fillUserAuthorizations(user, onSuccess(has -> {
      assertTrue(RoleBasedAuthorization.create("dev").match(user));
      testComplete();
    }));
  }));
  await();
}