Java Code Examples for io.vertx.ext.auth.jwt.JWTAuthOptions

The following examples show how to use io.vertx.ext.auth.jwt.JWTAuthOptions. 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: besu   Source File: AuthenticationService.java    License: Apache License 2.0 6 votes vote down vote up
private static Optional<AuthenticationService> create(
    final Vertx vertx,
    final boolean authenticationEnabled,
    final String authenticationCredentialsFile,
    final File authenticationPublicKeyFile) {
  if (!authenticationEnabled) {
    return Optional.empty();
  }

  final JWTAuthOptions jwtAuthOptions =
      authenticationPublicKeyFile == null
          ? jwtAuthOptionsFactory.createWithGeneratedKeyPair()
          : jwtAuthOptionsFactory.createForExternalPublicKey(authenticationPublicKeyFile);

  final Optional<AuthProvider> credentialAuthProvider =
      makeCredentialAuthProvider(vertx, authenticationEnabled, authenticationCredentialsFile);

  return Optional.of(
      new AuthenticationService(
          JWTAuth.create(vertx, jwtAuthOptions), jwtAuthOptions, credentialAuthProvider));
}
 
Example 2
Source Project: xyz-hub   Source File: XYZHubRESTVerticle.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add the security handlers.
 */
private AuthHandler createJWTHandler() {
  JWTAuthOptions authConfig = new JWTAuthOptions().addPubSecKey(
      new PubSecKeyOptions().setAlgorithm("RS256")
          .setPublicKey(Service.configuration.JWT_PUB_KEY));

  JWTAuth authProvider = new XyzAuthProvider(vertx, authConfig);

  ChainAuthHandler authHandler = ChainAuthHandler.create()
      .append(JWTAuthHandler.create(authProvider))
      .append(JWTURIHandler.create(authProvider));

  if (Service.configuration.XYZ_HUB_AUTH == AuthorizationType.DUMMY) {
    authHandler.append(JwtDummyHandler.create(authProvider));
  }

  return authHandler;
}
 
Example 3
Source Project: vertx-web   Source File: WebExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example50(Vertx vertx) {

    Router router = Router.router(vertx);

    JWTAuthOptions authConfig = new JWTAuthOptions()
      .setKeyStore(new KeyStoreOptions()
        .setType("jceks")
        .setPath("keystore.jceks")
        .setPassword("secret"));

    JWTAuth jwt = JWTAuth.create(vertx, authConfig);

    router.route("/login").handler(ctx -> {
      // this is an example, authentication should be done with another provider...
      if (
        "paulo".equals(ctx.request().getParam("username")) &&
          "secret".equals(ctx.request().getParam("password"))) {
        ctx.response()
          .end(jwt.generateToken(new JsonObject().put("sub", "paulo")));
      } else {
        ctx.fail(401);
      }
    });
  }
 
Example 4
Source Project: vertx-web   Source File: WebExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example51(Vertx vertx) {

    Router router = Router.router(vertx);

    JWTAuthOptions authConfig = new JWTAuthOptions()
      .setKeyStore(new KeyStoreOptions()
        .setType("jceks")
        .setPath("keystore.jceks")
        .setPassword("secret"));

    JWTAuth authProvider = JWTAuth.create(vertx, authConfig);

    router.route("/protected/*").handler(JWTAuthHandler.create(authProvider));

    router.route("/protected/somepage").handler(ctx -> {
      // some handle code...
    });
  }
 
Example 5
Source Project: vertx-web   Source File: WebExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example52(Vertx vertx) {

    JWTAuthOptions authConfig = new JWTAuthOptions()
      .setKeyStore(new KeyStoreOptions()
        .setType("jceks")
        .setPath("keystore.jceks")
        .setPassword("secret"));

    JWTAuth authProvider = JWTAuth.create(vertx, authConfig);

    authProvider
      .generateToken(
        new JsonObject()
          .put("sub", "paulo")
          .put("someKey", "some value"),
        new JWTOptions());
  }
 
Example 6
Source Project: vertx-service-proxy   Source File: Examples.java    License: 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 7
Source Project: vertx-auth   Source File: AuthJWTExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example7(Vertx vertx, String username, String password) {

    JWTAuthOptions config = new JWTAuthOptions()
      .setKeyStore(new KeyStoreOptions()
        .setPath("keystore.jceks")
        .setPassword("secret"));

    JWTAuth provider = JWTAuth.create(vertx, config);

    // on the verify endpoint once you verify the identity
    // of the user by its username/password
    if ("paulo".equals(username) && "super_secret".equals(password)) {
      String token = provider.generateToken(
        new JsonObject().put("sub", "paulo"), new JWTOptions());

      // now for any request to protected resources you should
      // pass this string in the HTTP header Authorization as:
      // Authorization: Bearer <token>
    }
  }
 
Example 8
Source Project: vertx-auth   Source File: AuthJWTExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example17(Vertx vertx) {
  JWTAuth provider = JWTAuth.create(vertx, new JWTAuthOptions()
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("ES256")
      .setBuffer(
        "-----BEGIN PRIVATE KEY-----\n" +
          "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgeRyEfU1NSHPTCuC9\n" +
          "rwLZMukaWCH2Fk6q5w+XBYrKtLihRANCAAStpUnwKmSvBM9EI+W5QN3ALpvz6bh0\n" +
          "SPCXyz5KfQZQuSj4f3l+xNERDUDaygIUdLjBXf/bc15ur2iZjcq4r0Mr\n" +
          "-----END PRIVATE KEY-----\n")
    ));

  String token = provider.generateToken(
    new JsonObject(),
    new JWTOptions().setAlgorithm("ES256"));
}
 
Example 9
Source Project: vertx-auth   Source File: AuthJWTExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example18(Vertx vertx) {
  JWTAuth provider = JWTAuth.create(vertx, new JWTAuthOptions()
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("ES256")
      .setBuffer(
        "-----BEGIN PUBLIC KEY-----\n" +
          "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEraVJ8CpkrwTPRCPluUDdwC6b8+m4\n" +
          "dEjwl8s+Sn0GULko+H95fsTREQ1A2soCFHS4wV3/23Nebq9omY3KuK9DKw==\n" +
          "-----END PUBLIC KEY-----"))
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(
        "-----BEGIN PRIVATE KEY-----\n" +
          "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgeRyEfU1NSHPTCuC9\n" +
          "rwLZMukaWCH2Fk6q5w+XBYrKtLihRANCAAStpUnwKmSvBM9EI+W5QN3ALpvz6bh0\n" +
          "SPCXyz5KfQZQuSj4f3l+xNERDUDaygIUdLjBXf/bc15ur2iZjcq4r0Mr")
    ));

  String token = provider.generateToken(
    new JsonObject(),
    new JWTOptions().setAlgorithm("ES256"));
}
 
Example 10
Source Project: vertx-auth   Source File: JWTAuthProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateNewTokenES256() {
  authProvider = JWTAuth.create(vertx, new JWTAuthOptions()
    .setKeyStore(new KeyStoreOptions()
      .setPath("es256-keystore.jceks")
      .setType("jceks")
      .setPassword("secret")));

  String token = authProvider.generateToken(new JsonObject().put("sub", "paulo"), new JWTOptions().setAlgorithm("ES256"));
  assertNotNull(token);

  TokenCredentials authInfo = new TokenCredentials(token);

  authProvider.authenticate(authInfo, res -> {
    if (res.failed()) {
      res.cause().printStackTrace();
      fail();
    }

    assertNotNull(res.result());
    testComplete();
  });
  await();
}
 
Example 11
Source Project: vertx-auth   Source File: JWTAuthProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateNewTokenWithMacSecret() {
  authProvider = JWTAuth.create(vertx, new JWTAuthOptions()
    .addJwk(new JsonObject()
      .put("kty", "oct")
      .put("k", "notasecret"))
  );

  String token = authProvider.generateToken(new JsonObject(), new JWTOptions().setAlgorithm("HS256"));
  assertNotNull(token);

  // reverse
  TokenCredentials authInfo = new TokenCredentials(token);
  authProvider.authenticate(authInfo, onSuccess(res -> {
    assertNotNull(res);
    testComplete();
  }));
  await();
}
 
Example 12
Source Project: vertx-auth   Source File: JWTAuthProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateNewTokenForceAlgorithm() {
  authProvider = JWTAuth.create(vertx, new JWTAuthOptions()
    .setKeyStore(new KeyStoreOptions()
      .setPath("keystore.jceks")
      .setType("jceks")
      .setPassword("secret")));

  String token = authProvider.generateToken(new JsonObject(), new JWTOptions().setAlgorithm("RS256"));
  assertNotNull(token);

  // reverse
  TokenCredentials authInfo = new TokenCredentials(token);
  authProvider.authenticate(authInfo, onSuccess(res -> {
    assertNotNull(res);
    testComplete();
  }));
  await();
}
 
Example 13
Source Project: vertx-auth   Source File: JWTAuthProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAlgNone() {

  JWTAuth authProvider = JWTAuth.create(vertx, new JWTAuthOptions());

  JsonObject payload = new JsonObject()
    .put("sub", "UserUnderTest")
    .put("aud", "OrganizationUnderTest")
    .put("iat", 1431695313)
    .put("exp", 1747055313)
    .put("roles", new JsonArray().add("admin").add("developer").add("user"))
    .put("permissions", new JsonArray().add("read").add("write").add("execute"));

  final String token = authProvider.generateToken(payload, new JWTOptions().setSubject("UserUnderTest").setAlgorithm("none"));
  assertNotNull(token);

  TokenCredentials authInfo = new TokenCredentials(token);

  authProvider.authenticate(authInfo, onSuccess(res -> {
    assertNotNull(res);
    testComplete();
  }));
  await();
}
 
Example 14
Source Project: besu   Source File: JWTAuthOptionsFactory.java    License: Apache License 2.0 5 votes vote down vote up
public JWTAuthOptions createForExternalPublicKey(final File externalPublicKeyFile) {
  final byte[] externalJwtPublicKey = readPublicKey(externalPublicKeyFile);
  final String base64EncodedPublicKey = Base64.getEncoder().encodeToString(externalJwtPublicKey);
  return new JWTAuthOptions()
      .setPermissionsClaimKey(PERMISSIONS)
      .addPubSecKey(
          new PubSecKeyOptions().setAlgorithm(ALGORITHM).setPublicKey(base64EncodedPublicKey));
}
 
Example 15
Source Project: besu   Source File: JWTAuthOptionsFactory.java    License: Apache License 2.0 5 votes vote down vote up
public JWTAuthOptions createWithGeneratedKeyPair() {
  final KeyPair keypair = generateJwtKeyPair();
  return new JWTAuthOptions()
      .setPermissionsClaimKey(PERMISSIONS)
      .addPubSecKey(
          new PubSecKeyOptions()
              .setAlgorithm(ALGORITHM)
              .setPublicKey(Base64.getEncoder().encodeToString(keypair.getPublic().getEncoded()))
              .setSecretKey(
                  Base64.getEncoder().encodeToString(keypair.getPrivate().getEncoded())));
}
 
Example 16
Source Project: besu   Source File: AuthenticationService.java    License: Apache License 2.0 5 votes vote down vote up
private AuthenticationService(
    final JWTAuth jwtAuthProvider,
    final JWTAuthOptions jwtAuthOptions,
    final Optional<AuthProvider> credentialAuthProvider) {
  this.jwtAuthProvider = jwtAuthProvider;
  this.jwtAuthOptions = jwtAuthOptions;
  this.credentialAuthProvider = credentialAuthProvider;
}
 
Example 17
Source Project: besu   Source File: JWTAuthOptionsFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createsOptionsWithGeneratedKeyPair() {
  final JWTAuthOptionsFactory jwtAuthOptionsFactory = new JWTAuthOptionsFactory();
  final JWTAuthOptions jwtAuthOptions = jwtAuthOptionsFactory.createWithGeneratedKeyPair();

  assertThat(jwtAuthOptions.getPubSecKeys()).isNotNull();
  assertThat(jwtAuthOptions.getPubSecKeys()).hasSize(1);
  assertThat(jwtAuthOptions.getPubSecKeys().get(0).getAlgorithm()).isEqualTo("RS256");
  assertThat(jwtAuthOptions.getPubSecKeys().get(0).getPublicKey()).isNotEmpty();
  assertThat(jwtAuthOptions.getPubSecKeys().get(0).getSecretKey()).isNotEmpty();
}
 
Example 18
Source Project: besu   Source File: JWTAuthOptionsFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createsOptionsWithGeneratedKeyPairThatIsDifferentEachTime() {
  final JWTAuthOptionsFactory jwtAuthOptionsFactory = new JWTAuthOptionsFactory();
  final JWTAuthOptions jwtAuthOptions1 = jwtAuthOptionsFactory.createWithGeneratedKeyPair();
  final JWTAuthOptions jwtAuthOptions2 = jwtAuthOptionsFactory.createWithGeneratedKeyPair();

  final PubSecKeyOptions pubSecKeyOptions1 = jwtAuthOptions1.getPubSecKeys().get(0);
  final PubSecKeyOptions pubSecKeyOptions2 = jwtAuthOptions2.getPubSecKeys().get(0);
  assertThat(pubSecKeyOptions1.getPublicKey()).isNotEqualTo(pubSecKeyOptions2.getPublicKey());
  assertThat(pubSecKeyOptions1.getSecretKey()).isNotEqualTo(pubSecKeyOptions2.getSecretKey());
}
 
Example 19
Source Project: besu   Source File: JWTAuthOptionsFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createsOptionsUsingPublicKeyFile() throws URISyntaxException {
  final JWTAuthOptionsFactory jwtAuthOptionsFactory = new JWTAuthOptionsFactory();
  final File enclavePublicKeyFile =
      Paths.get(ClassLoader.getSystemResource("authentication/jwt_public_key").toURI())
          .toAbsolutePath()
          .toFile();

  final JWTAuthOptions jwtAuthOptions =
      jwtAuthOptionsFactory.createForExternalPublicKey(enclavePublicKeyFile);
  assertThat(jwtAuthOptions.getPubSecKeys()).hasSize(1);
  assertThat(jwtAuthOptions.getPubSecKeys().get(0).getAlgorithm()).isEqualTo("RS256");
  assertThat(jwtAuthOptions.getPubSecKeys().get(0).getSecretKey()).isNull();
  assertThat(jwtAuthOptions.getPubSecKeys().get(0).getPublicKey()).isEqualTo(JWT_PUBLIC_KEY);
}
 
Example 20
Source Project: besu   Source File: AuthenticationUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getUserFailsIfTokenDoesNotHaveExpiryClaim() {
  final AuthenticationService authenticationService = mock(AuthenticationService.class);
  final JWTAuth jwtAuth = new JWTAuthProviderImpl(null, new JWTAuthOptions());
  final StubUserHandler handler = new StubUserHandler();
  when(authenticationService.getJwtAuthProvider()).thenReturn(jwtAuth);

  AuthenticationUtils.getUser(
      Optional.of(authenticationService), INVALID_TOKEN_WITHOUT_EXP, handler);

  assertThat(handler.getEvent()).isEmpty();
}
 
Example 21
Source Project: besu   Source File: AuthenticationUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getUserSucceedsWithValidToken() {
  final AuthenticationService authenticationService = mock(AuthenticationService.class);
  final JWTAuth jwtAuth = new JWTAuthProviderImpl(null, new JWTAuthOptions());
  final StubUserHandler handler = new StubUserHandler();
  when(authenticationService.getJwtAuthProvider()).thenReturn(jwtAuth);

  AuthenticationUtils.getUser(Optional.of(authenticationService), VALID_TOKEN, handler);

  assertThat(handler.getEvent().get().principal())
      .isEqualTo(new JsonObject(VALID_TOKEN_DECODED_PAYLOAD));
}
 
Example 22
Source Project: xyz-hub   Source File: JwtGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static void setup() throws IOException {
  JWTAuthOptions authConfig = new JWTAuthOptions()
      .setJWTOptions(jwtOptions)
      .addPubSecKey(new PubSecKeyOptions()
          .setAlgorithm("RS256")
          .setPublicKey(readResourceFile("/auth/jwt.pub"))
          .setSecretKey(readResourceFile("/auth/jwt.key")));

  authProvider = JWTAuth.create(Service.vertx, authConfig);
}
 
Example 23
Source Project: redpipe   Source File: WikiServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected AuthProvider setupAuthenticationRoutes() {
	JsonObject keycloackConfig = AppGlobals.get().getConfig().getJsonObject("keycloack");
	OAuth2Auth authWeb = KeycloakAuth.create(AppGlobals.get().getVertx(), keycloackConfig);
	OAuth2Auth authApi = KeycloakAuth.create(AppGlobals.get().getVertx(), OAuth2FlowType.PASSWORD, keycloackConfig);
	
	// FIXME: URL
	OAuth2AuthHandler authHandler = OAuth2AuthHandler.create((OAuth2Auth) authWeb, "http://localhost:9000/callback");
	Router router = AppGlobals.get().getRouter();
	// FIXME: crazy!!
	AuthProvider authProvider = AuthProvider.newInstance(authWeb.getDelegate());
	router.route().handler(UserSessionHandler.create(authProvider));

	authHandler.setupCallback(router.get("/callback"));
	
	JWTAuth jwtAuth = JWTAuth.create(AppGlobals.get().getVertx(), new JWTAuthOptions(new JsonObject()
			.put("keyStore", AppGlobals.get().getConfig().getJsonObject("keystore"))));
	AppGlobals.get().setGlobal(JWTAuth.class, jwtAuth);
	
	JWTAuthHandler jwtAuthHandler = JWTAuthHandler.create(jwtAuth, "/wiki/api/token");

	// FIXME: just use different routers
	router.route().handler(ctx -> {
		if(!ctx.request().uri().startsWith("/wiki/api/"))
			authHandler.handle(ctx);
		else
			jwtAuthHandler.handle(ctx);
	});
	
	return AuthProvider.newInstance(authApi.getDelegate());
}
 
Example 24
Source Project: redpipe   Source File: WikiServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected AuthProvider setupAuthenticationRoutes() {
	AppGlobals globals = AppGlobals.get();
	AuthProvider auth = ShiroAuth.create(globals.getVertx(), new ShiroAuthOptions()
			.setType(ShiroAuthRealmType.PROPERTIES)
			.setConfig(new JsonObject()
					.put("properties_path", globals.getConfig().getString("security_definitions"))));
	
	globals.getRouter().route().handler(UserSessionHandler.create(auth));

	
	JsonObject keyStoreOptions = new JsonObject().put("keyStore", globals.getConfig().getJsonObject("keystore"));
	
	// attempt to load a Key file
	JWTAuth jwtAuth = JWTAuth.create(globals.getVertx(), new JWTAuthOptions(keyStoreOptions));
	JWTAuthHandler jwtAuthHandler = JWTAuthHandler.create(jwtAuth);

	globals.setGlobal(JWTAuth.class, jwtAuth);
	globals.getRouter().route().handler(context -> {
		// only filter if we have a header, otherwise it will try to force auth, regardless if whether
		// we want auth
		if(context.request().getHeader(HttpHeaders.AUTHORIZATION) != null)
			jwtAuthHandler.handle(context);
		else
			context.next();
	});

	return auth;
}
 
Example 25
Source Project: vertx-web   Source File: JWTAuthHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  JsonObject authConfig = new JsonObject().put("keyStore", new JsonObject()
      .put("type", "jceks")
      .put("path", "keystore.jceks")
      .put("password", "secret"));

  authProvider = JWTAuth.create(vertx, new JWTAuthOptions(authConfig));
}
 
Example 26
Source Project: vertx-web   Source File: MultiAuthorizationHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  JsonObject authConfig = new JsonObject().put("keyStore",
      new JsonObject().put("type", "jceks").put("path", "keystore.jceks").put("password", "secret"));

  authProvider = JWTAuth.create(vertx, new JWTAuthOptions(authConfig));
}
 
Example 27
private JWTAuthOptions getJWTConfig() {
  return new JWTAuthOptions()
    .setKeyStore(new KeyStoreOptions()
      .setPath("keystore.jceks")
      .setType("jceks")
      .setPassword("secret"));
}
 
Example 28
Source Project: vertx-auth   Source File: AuthJWTExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void example6(Vertx vertx) {

    JWTAuthOptions config = new JWTAuthOptions()
      .setKeyStore(new KeyStoreOptions()
        .setPath("keystore.jceks")
        .setPassword("secret"));

    AuthenticationProvider provider = JWTAuth.create(vertx, config);
  }
 
Example 29
Source Project: vertx-auth   Source File: AuthJWTExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void example8(Vertx vertx) {

    JWTAuthOptions config = new JWTAuthOptions()
      .addPubSecKey(new PubSecKeyOptions()
        .setAlgorithm("RS256")
        .setBuffer("BASE64-ENCODED-PUBLIC_KEY"));

    AuthenticationProvider provider = JWTAuth.create(vertx, config);
  }
 
Example 30
Source Project: vertx-auth   Source File: AuthJWTExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void example14(Vertx vertx) {

    JsonObject config = new JsonObject()
      .put("public-key", "BASE64-ENCODED-PUBLIC_KEY")
      // since we're consuming keycloak JWTs we need
      // to locate the permission claims in the token
      .put("permissionsClaimKey", "realm_access/roles");

    AuthenticationProvider provider =
      JWTAuth.create(vertx, new JWTAuthOptions(config));
  }