io.vertx.ext.auth.PubSecKeyOptions Java Examples

The following examples show how to use io.vertx.ext.auth.PubSecKeyOptions. 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: AuthJWTExamples.java    From vertx-auth with 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 #2
Source File: XYZHubRESTVerticle.java    From xyz-hub with 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 File: AuthJWTExamples.java    From vertx-auth with 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 #4
Source File: GoogleAuth.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Google Service Account (Server to Server)
 *
 * @param serviceAccountJson the configuration json file from your Google API page
 * @param httpClientOptions  custom http client options
 */
static OAuth2Auth create(Vertx vertx, JsonObject serviceAccountJson, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_JWT)
      .setClientID(serviceAccountJson.getString("client_id"))
      .setSite("https://accounts.google.com")
      .setTokenPath(serviceAccountJson.getString("token_uri"))
      .addPubSecKey(new PubSecKeyOptions()
        .setAlgorithm("RS256")
        .setBuffer(serviceAccountJson.getString("private_key")))
      .setJWTOptions(new JWTOptions()
        .setAlgorithm("RS256")
        .setExpiresInMinutes(60)
        .addAudience(serviceAccountJson.getString("token_uri"))
        .setIssuer(serviceAccountJson.getString("client_email"))));
}
 
Example #5
Source File: Oauth2TokenScopeTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Scopes are available into the token but no scopes requirement is set.
 */
@Test
public void shouldNotFailWhenNoScopeRequired() {
  config = new JsonObject()
    .put("token_type", "Bearer")
    .put("access_token", JWT)
    .put("token", JWT);

  oauthConfig
    .addPubSecKey(new PubSecKeyOptions().setAlgorithm("HS256").setBuffer("vertx").setSymmetric(true));

  oauth2 = OAuth2Auth.create(vertx, oauthConfig);

  oauth2.authenticate(config, res -> {
    if (res.failed()) {
      fail("Test should have not failed");
    } else {
      User token = res.result();
      testComplete();
    }
  });
  await();
}
 
Example #6
Source File: Oauth2TokenScopeTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Token scopes are checked and scopeX is missing.
 * Scopes are retrieved from the JWT itself.
 * JWT generated in HS256 with vertx as shared secret.
 */
@Test
public void tokenIsNotValid() {
  config = new JsonObject()
    .put("token_type", "Bearer")
    .put("access_token", JWT)
    .put("token", JWT);

  oauthConfig
    .addPubSecKey(new PubSecKeyOptions().setAlgorithm("HS256").setBuffer("vertx").setSymmetric(true))
    .setJWTOptions(new JWTOptions().addScope("scopeX").addScope("scopeB"));

  oauth2 = OAuth2Auth.create(vertx, oauthConfig);

  oauth2.authenticate(config, res -> {
    assertTrue(res.succeeded());
    ScopeAuthorization.create(" ").getAuthorizations(res.result(), call -> {
      assertTrue(call.succeeded());
      // the scopes are missing
      assertFalse(PermissionBasedAuthorization.create("scopeX").match(res.result()));
      assertFalse(PermissionBasedAuthorization.create("scopeB").match(res.result()));
      testComplete();
    });
  });
  await();
}
 
Example #7
Source File: Oauth2TokenScopeTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Token scopes are checked and must be valid.
 * Scopes are retrieved from the JWT itself.
 * JWT generated in HS256 with vertx as shared secret.
 */
@Test
public void tokenIsValid() {
  config = new JsonObject()
    .put("token_type", "Bearer")
    .put("access_token", JWT)
    .put("token", JWT);

  oauthConfig
    .addPubSecKey(new PubSecKeyOptions().setAlgorithm("HS256").setBuffer("vertx").setSymmetric(true))
    .setJWTOptions(new JWTOptions().addScope("scopeA").addScope("scopeB"));

  oauth2 = OAuth2Auth.create(vertx, oauthConfig);

  oauth2.authenticate(config, res -> {
    if (res.failed()) {
      fail(res.cause());
    } else {
      User token = res.result();
      assertFalse(token.expired());
      testComplete();
    }
  });
  await();
}
 
Example #8
Source File: JWTAuthOptionsFactory.java    From besu with 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 #9
Source File: JWTAuthOptions.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public JWTAuthOptions addPubSecKey(PubSecKeyOptions pubSecKey) {
  if (this.pubSecKeys == null) {
    this.pubSecKeys = new ArrayList<>();
  }
  this.pubSecKeys.add(pubSecKey);
  return this;
}
 
Example #10
Source File: AuthJWTExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example16(Vertx vertx) {
  JWTAuth provider = JWTAuth.create(vertx, new JWTAuthOptions()
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("HS256")
      .setBuffer("keyboard cat")));

  String token = provider.generateToken(new JsonObject());
}
 
Example #11
Source File: AuthJWTExamples.java    From vertx-auth with 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 #12
Source File: CryptoTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void ecdsaSignatureComplianceTest() throws Exception {

  JWT jwt = new JWT()
    .addJWK(new JWK(
      new PubSecKeyOptions()
        .setAlgorithm("ES512")
        .setBuffer("-----BEGIN PUBLIC KEY-----\nMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQASisgweVL1tAtIvfmpoqvdXF8sPKTV9YTKNxBwkdkm+/auh4pR8TbaIfsEzcsGUVv61DFNFXb0ozJfurQ59G2XcgAn3vROlSSnpbIvuhKrzL5jwWDTaYa5tVF1Zjwia/5HUhKBkcPuWGXg05nMjWhZfCuEetzMLoGcHmtvabugFrqsAg=\n-----END PUBLIC KEY-----\n")));

  assertFalse(jwt.isUnsecure());
  //Test verification for token created using https://github.com/auth0/node-jsonwebtoken/tree/v7.0.1
  assertNotNull(jwt.decode("eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJ0ZXN0IjoidGVzdCIsImlhdCI6MTQ2NzA2NTgyN30.Aab4x7HNRzetjgZ88AMGdYV2Ml7kzFbl8Ql2zXvBores7iRqm2nK6810ANpVo5okhHa82MQf2Q_Zn4tFyLDR9z4GAcKFdcAtopxq1h8X58qBWgNOc0Bn40SsgUc8wOX4rFohUCzEtnUREePsvc9EfXjjAH78WD2nq4tn-N94vf14SncQ"));
  //Test verification for token created using https://github.com/jwt/ruby-jwt/tree/v1.5.4
  assertNotNull(jwt.decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJ0ZXN0IjoidGVzdCJ9.AV26tERbSEwcoDGshneZmhokg-tAKUk0uQBoHBohveEd51D5f6EIs6cskkgwtfzs4qAGfx2rYxqQXr7LTXCNquKiAJNkTIKVddbPfped3_TQtmHZTmMNiqmWjiFj7Y9eTPMMRRu26w4gD1a8EQcBF-7UGgeH4L_1CwHJWAXGbtu7uMUn"));
}
 
Example #13
Source File: OAuth2Options.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public OAuth2Options addPubSecKey(PubSecKeyOptions pubSecKey) {
  if (pubSecKeys == null) {
    pubSecKeys = new ArrayList<>();
  }
  pubSecKeys.add(pubSecKey);
  return this;
}
 
Example #14
Source File: OAuth2AuthProviderImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public OAuth2AuthProviderImpl(Vertx vertx, OAuth2Options config) {
  this.vertx = vertx;
  this.config = config;
  this.api = new OAuth2API(vertx, config);
  // compute paths with variables, at this moment it is only relevant that
  // all variables are properly computed
  this.config.replaceVariables(true);
  this.config.validate();

  if (config.getPubSecKeys() != null) {
    for (PubSecKeyOptions pubSecKey : config.getPubSecKeys()) {
      jwt.addJWK(new JWK(pubSecKey));
    }
  }
}
 
Example #15
Source File: OidcRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private TenantConfigContext createdTenantContextFromPublicKey(OAuth2ClientOptions options, OidcTenantConfig oidcConfig) {
    if (oidcConfig.applicationType == ApplicationType.WEB_APP) {
        throw new ConfigurationException("'public-key' property can only be used with the 'service' applications");
    }
    LOG.debug("'public-key' property for the local token verification is set,"
            + " no connection to the OIDC server will be created");
    options.addPubSecKey(new PubSecKeyOptions()
            .setAlgorithm("RS256")
            .setPublicKey(oidcConfig.getPublicKey().get()));

    return new TenantConfigContext(new OAuth2AuthProviderImpl(null, options), oidcConfig);
}
 
Example #16
Source File: JwtGenerator.java    From xyz-hub with 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 #17
Source File: JWTAuthOptionsFactoryTest.java    From besu with 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 #18
Source File: JWTAuthOptionsFactory.java    From besu with 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 #19
Source File: OAuth2Options.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public OAuth2Options setPubSecKeys(List<PubSecKeyOptions> pubSecKeys) {
  this.pubSecKeys = pubSecKeys;
  return this;
}
 
Example #20
Source File: KeycloakAuth.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Keycloak
 *
 * @param flow              the oauth2 flow to use
 * @param config            the json config file exported from Keycloak admin console
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, OAuth2FlowType flow, JsonObject config, HttpClientOptions httpClientOptions) {
  final OAuth2Options options = new OAuth2Options()
    .setHttpClientOptions(httpClientOptions);

  options.setFlow(flow);

  if (config.containsKey("resource")) {
    options.setClientID(config.getString("resource"));
  }

  // keycloak conversion to oauth2 options
  if (config.containsKey("auth-server-url")) {
    options.setSite(config.getString("auth-server-url"));
  }

  if (config.containsKey("credentials") && config.getJsonObject("credentials").containsKey("secret")) {
    options.setClientSecret(config.getJsonObject("credentials").getString("secret"));
  }

  if (config.containsKey("public-client") && config.getBoolean("public-client", false)) {
    options.setUseBasicAuthorizationHeader(true);
  }

  if (config.containsKey("realm")) {
    final String realm = config.getString("realm");

    options.setAuthorizationPath("/realms/" + realm + "/protocol/openid-connect/auth");
    options.setTokenPath("/realms/" + realm + "/protocol/openid-connect/token");
    options.setRevocationPath(null);
    options.setLogoutPath("/realms/" + realm + "/protocol/openid-connect/logout");
    options.setUserInfoPath("/realms/" + realm + "/protocol/openid-connect/userinfo");
    // keycloak follows the RFC7662
    options.setIntrospectionPath("/realms/" + realm + "/protocol/openid-connect/token/introspect");
    // keycloak follows the RFC7517
    options.setJwkPath("/realms/" + realm + "/protocol/openid-connect/certs");
  }

  if (config.containsKey("realm-public-key")) {
    options.addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setPublicKey(config.getString("realm-public-key")));
  }

  return OAuth2Auth
    .create(vertx, options)
    .rbacHandler(KeycloakRBAC.create(options));
}
 
Example #21
Source File: AuthJWTExamples.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public void example15(Vertx vertx) {
  JWTAuth provider = JWTAuth.create(vertx, new JWTAuthOptions()
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(
        "-----BEGIN PUBLIC KEY-----\n" +
          "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxPSbCQY5mBKFDIn1kggv\n" +
          "Wb4ChjrctqD4nFnJOJk4mpuZ/u3h2ZgeKJJkJv8+5oFO6vsEwF7/TqKXp0XDp6IH\n" +
          "byaOSWdkl535rCYR5AxDSjwnuSXsSp54pvB+fEEFDPFF81GHixepIbqXCB+BnCTg\n" +
          "N65BqwNn/1Vgqv6+H3nweNlbTv8e/scEgbg6ZYcsnBBB9kYLp69FSwNWpvPmd60e\n" +
          "3DWyIo3WCUmKlQgjHL4PHLKYwwKgOHG/aNl4hN4/wqTixCAHe6KdLnehLn71x+Z0\n" +
          "SyXbWooftefpJP1wMbwlCpH3ikBzVIfHKLWT9QIOVoRgchPU3WAsZv/ePgl5i8Co\n" +
          "qwIDAQAB\n" +
          "-----END PUBLIC KEY-----"))
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(
        "-----BEGIN PRIVATE KEY-----\n" +
          "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDE9JsJBjmYEoUM\n" +
          "ifWSCC9ZvgKGOty2oPicWck4mTiam5n+7eHZmB4okmQm/z7mgU7q+wTAXv9Oopen\n" +
          "RcOnogdvJo5JZ2SXnfmsJhHkDENKPCe5JexKnnim8H58QQUM8UXzUYeLF6khupcI\n" +
          "H4GcJOA3rkGrA2f/VWCq/r4fefB42VtO/x7+xwSBuDplhyycEEH2Rgunr0VLA1am\n" +
          "8+Z3rR7cNbIijdYJSYqVCCMcvg8cspjDAqA4cb9o2XiE3j/CpOLEIAd7op0ud6Eu\n" +
          "fvXH5nRLJdtaih+15+kk/XAxvCUKkfeKQHNUh8cotZP1Ag5WhGByE9TdYCxm/94+\n" +
          "CXmLwKirAgMBAAECggEAeQ+M+BgOcK35gAKQoklLqZLEhHNL1SnOhnQd3h84DrhU\n" +
          "CMF5UEFTUEbjLqE3rYGP25mdiw0ZSuFf7B5SrAhJH4YIcZAO4a7ll23zE0SCW+/r\n" +
          "zr9DpX4Q1TP/2yowC4uGHpBfixxpBmVljkWnai20cCU5Ef/O/cAh4hkhDcHrEKwb\n" +
          "m9nymKQt06YnvpCMKoHDdqzfB3eByoAKuGxo/sbi5LDpWalCabcg7w+WKIEU1PHb\n" +
          "Qi+RiDf3TzbQ6TYhAEH2rKM9JHbp02TO/r3QOoqHMITW6FKYvfiVFN+voS5zzAO3\n" +
          "c5X4I+ICNzm+mnt8wElV1B6nO2hFg2PE9uVnlgB2GQKBgQD8xkjNhERaT7f78gBl\n" +
          "ch15DRDH0m1rz84PKRznoPrSEY/HlWddlGkn0sTnbVYKXVTvNytKSmznRZ7fSTJB\n" +
          "2IhQV7+I0jeb7pyLllF5PdSQqKTk6oCeL8h8eDPN7awZ731zff1AGgJ3DJXlRTh/\n" +
          "O6zj9nI8llvGzP30274I2/+cdwKBgQDHd/twbiHZZTDexYewP0ufQDtZP1Nk54fj\n" +
          "EpkEuoTdEPymRoq7xo+Lqj5ewhAtVKQuz6aH4BeEtSCHhxy8OFLDBdoGCEd/WBpD\n" +
          "f+82sfmGk+FxLyYkLxHCxsZdOb93zkUXPCoCrvNRaUFO1qq5Dk8eftGCdC3iETHE\n" +
          "6h5avxHGbQKBgQCLHQVMNhL4MQ9slU8qhZc627n0fxbBUuhw54uE3s+rdQbQLKVq\n" +
          "lxcYV6MOStojciIgVRh6FmPBFEvPTxVdr7G1pdU/k5IPO07kc6H7O9AUnPvDEFwg\n" +
          "suN/vRelqbwhufAs85XBBY99vWtxdpsVSt5nx2YvegCgdIj/jUAU2B7hGQKBgEgV\n" +
          "sCRdaJYr35FiSTsEZMvUZp5GKFka4xzIp8vxq/pIHUXp0FEz3MRYbdnIwBfhssPH\n" +
          "/yKzdUxcOLlBtry+jgo0nyn26/+1Uyh5n3VgtBBSePJyW5JQAFcnhqBCMlOVk5pl\n" +
          "/7igiQYux486PNBLv4QByK0gV0SPejDzeqzIyB+xAoGAe5if7DAAKhH0r2M8vTkm\n" +
          "JvbCFjwuvhjuI+A8AuS8zw634BHne2a1Fkvc8c3d9VDbqsHCtv2tVkxkKXPjVvtB\n" +
          "DtzuwUbp6ebF+jOfPK0LDuJoTdTdiNjIcXJ7iTTI3cXUnUNWWphYnFogzPFq9CyL\n" +
          "0fPinYmDJpkwMYHqQaLGQyg=\n" +
          "-----END PRIVATE KEY-----")
    ));

  String token = provider.generateToken(
    new JsonObject().put("some", "token-data"),
    new JWTOptions().setAlgorithm("RS256"));
}
 
Example #22
Source File: PublicApiVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
@Override
public Completable rxStart() {

  String publicKey;
  String privateKey;
  try {
    publicKey = CryptoHelper.publicKey();
    privateKey = CryptoHelper.privateKey();
  } catch (IOException e) {
    return Completable.error(e);
  }

  jwtAuth = JWTAuth.create(vertx, new JWTAuthOptions()
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(publicKey))
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(privateKey)));

  Router router = Router.router(vertx);

  Set<String> allowedHeaders = new HashSet<>();
  allowedHeaders.add("x-requested-with");
  allowedHeaders.add("Access-Control-Allow-Origin");
  allowedHeaders.add("origin");
  allowedHeaders.add("Content-Type");
  allowedHeaders.add("accept");
  allowedHeaders.add("Authorization");

  Set<HttpMethod> allowedMethods = new HashSet<>();
  allowedMethods.add(HttpMethod.GET);
  allowedMethods.add(HttpMethod.POST);
  allowedMethods.add(HttpMethod.OPTIONS);
  allowedMethods.add(HttpMethod.PUT);

  router.route().handler(CorsHandler
    .create("*")
    .allowedHeaders(allowedHeaders)
    .allowedMethods(allowedMethods));

  BodyHandler bodyHandler = BodyHandler.create();
  router.post().handler(bodyHandler);
  router.put().handler(bodyHandler);

  String prefix = "/api/v1";
  JWTAuthHandler jwtHandler = JWTAuthHandler.create(jwtAuth);

  // Account
  router.post(prefix + "/register").handler(this::register);
  router.post(prefix + "/token").handler(this::token);

  // Profile
  router.get(prefix + "/:username").handler(jwtHandler).handler(this::checkUser).handler(this::fetchUser);
  router.put(prefix + "/:username").handler(jwtHandler).handler(this::checkUser).handler(this::updateUser);

  // Data
  router.get(prefix + "/:username/total").handler(jwtHandler).handler(this::checkUser).handler(this::totalSteps);
  router.get(prefix + "/:username/:year/:month").handler(jwtHandler).handler(this::checkUser).handler(this::monthlySteps);
  router.get(prefix + "/:username/:year/:month/:day").handler(jwtHandler).handler(this::checkUser).handler(this::dailySteps);

  webClient = WebClient.create(vertx);

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example #23
Source File: JWTAuthOptions.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public List<PubSecKeyOptions> getPubSecKeys() {
  return pubSecKeys;
}
 
Example #24
Source File: JWTAuthOptions.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public JWTAuthOptions setPubSecKeys(List<PubSecKeyOptions> pubSecKeys) {
  this.pubSecKeys = pubSecKeys;
  return this;
}
 
Example #25
Source File: JWTAuthProviderImpl.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public JWTAuthProviderImpl(Vertx vertx, JWTAuthOptions config) {
  this.permissionsClaimKey = config.getPermissionsClaimKey();
  this.jwtOptions = config.getJWTOptions();

  final KeyStoreOptions keyStore = config.getKeyStore();

  // attempt to load a Key file
  try {
    if (keyStore != null) {
      KeyStore ks = KeyStore.getInstance(keyStore.getType());

      // synchronize on the class to avoid the case where multiple file accesses will overlap
      synchronized (JWTAuthProviderImpl.class) {
        final Buffer keystore = vertx.fileSystem().readFileBlocking(keyStore.getPath());

        try (InputStream in = new ByteArrayInputStream(keystore.getBytes())) {
          ks.load(in, keyStore.getPassword().toCharArray());
        }
      }
      // load all available keys in the keystore
      for (JWK key : JWK.load(ks, keyStore.getPassword(), keyStore.getPasswordProtection())) {
        jwt.addJWK(key);
      }
    }
    // attempt to load pem keys
    final List<PubSecKeyOptions> keys = config.getPubSecKeys();

    if (keys != null) {
      for (PubSecKeyOptions pubSecKey : config.getPubSecKeys()) {
        jwt.addJWK(new JWK(pubSecKey));
      }
    }

    // attempt to load jwks
    final List<JsonObject> jwks = config.getJwks();

    if (jwks != null) {
      for (JsonObject jwk : jwks) {
        this.jwt.addJWK(new JWK(jwk));
      }
    }

  } catch (KeyStoreException | IOException | FileSystemException | CertificateException | NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 
Example #26
Source File: OAuth2Options.java    From vertx-auth with Apache License 2.0 2 votes vote down vote up
/**
 * The provider PubSec key options
 * @return the pub sec key options
 */
public List<PubSecKeyOptions> getPubSecKeys() {
  return pubSecKeys;
}