Search in sources :

Example 11 with OAuth2Options

use of io.vertx.ext.auth.oauth2.OAuth2Options in project vertx-web by vert-x3.

the class OAuth2AuthHandlerTest method testBearerOnlyWithJWT.

@Test
public void testBearerOnlyWithJWT() throws Exception {
    OAuth2Auth oauth = OAuth2Auth.create(vertx, new OAuth2Options().setClientId("s6BhdRkqt3").addPubSecKey(new PubSecKeyOptions().setAlgorithm("RS256").setBuffer("-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmuIC9Qvwoe/3tUpHkcUp\n" + "vWmzQqnZtz3HBKbxzc/jBTxUHefJDs88Xjw5nNXhl4tXkHzFRAZHtDnwX074/2oc\n" + "PRSWaBjHYXB771af91UPrc9fb4lh3W1a8hmQU6sgKlQVwDnUuePDkCmwKCsuyX0M\n" + "wxuwOwEUo4r15NBh/H7FvuHVPnqWK1/kliYtQukF3svQkpZT6/puQ0bEOefROLB+\n" + "EAPM0OAaDyknjxCZJenk9FIyC6skOKVaxW7CcE54lIUjS1GKFQc44/+T+u0VKSmh\n" + "rRdBNcAhXmdpwjLoDTy/I8z+uqkKitdEVczCdleNqeb6b1kjPWS3VbLXxY/LIYlz\n" + "uQIDAQAB\n" + "-----END PUBLIC KEY-----")));
    assertNotNull(oauth);
    JWT jwt = new JWT().addJWK(new JWK(new PubSecKeyOptions().setAlgorithm("RS256").setBuffer("-----BEGIN PRIVATE KEY-----\n" + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCa4gL1C/Ch7/e1\n" + "SkeRxSm9abNCqdm3PccEpvHNz+MFPFQd58kOzzxePDmc1eGXi1eQfMVEBke0OfBf\n" + "Tvj/ahw9FJZoGMdhcHvvVp/3VQ+tz19viWHdbVryGZBTqyAqVBXAOdS548OQKbAo\n" + "Ky7JfQzDG7A7ARSjivXk0GH8fsW+4dU+epYrX+SWJi1C6QXey9CSllPr+m5DRsQ5\n" + "59E4sH4QA8zQ4B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AoGAe6F4\n" + "+QLIwL1dSOMoGctBS4QU55so23e41fNJ2CpCf1uqPPn2Y9DOI/aYpxbv6n20xMTI\n" + "O2+of37h6h1lUhX38XGZ7YOm15sn5ZTJ/whZuDbFzh9HZ0N6oTq7vyOelPO8WblJ\n" + "077pgyRBQ51mhzGqKFVayPnUVZ/Ais7oEyxycU0CgYEAzEUhmN22ykywh0My83z/\n" + "7yl2tyrlv2hcZbaP7+9eHdUafGG8jMTVD7jxhzAbiSo2UeyHUnAItDnLetLh89K6\n" + "0oF3/rZLqugtb+f48dgRE/SDF4Itgp5fDqWHLhEW7ZhWCFlFgZ3sq0XryIxzFof0\n" + "O/Fd1NnotirzTnob5ReblIM=\n" + "-----END PRIVATE KEY-----\n")));
    assertNotNull(jwt);
    // lets mock a oauth2 server using code auth code flow
    OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler.create(vertx, oauth);
    // protect everything under /protected
    router.route("/protected/*").handler(oauth2Handler);
    // mount some handler under the protected zone
    router.route("/protected/somepage").handler(rc -> {
        assertNotNull(rc.user());
        rc.response().end("Welcome to the protected resource!");
    });
    testRequest(HttpMethod.GET, "/protected/somepage", 401, "Unauthorized");
    // Now try again with fake credentials
    testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("Authorization", "Bearer 4adc339e0"), 401, "Unauthorized", "Unauthorized");
    // Now try again with real credentials
    String accessToken = jwt.sign(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\": \"jdoe@server.example.com\",\n" + "      \"groups\": [\"red-group\", \"green-group\", \"admin-group\", \"admin\"]\n" + "}"), new JWTOptions().setAlgorithm("RS256"));
    testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("Authorization", "Bearer " + accessToken), 200, "OK", "Welcome to the protected resource!");
    // Now try again with expired credentials
    String accessTokenExp = jwt.sign(new JsonObject("{\n" + "      \"iss\": \"https://server.example.com\",\n" + "      \"aud\": \"s6BhdRkqt3\",\n" + "      \"jti\": \"a-123\",\n" + "      \"exp\": 1311280970,\n" + "      \"iat\": 1311280970,\n" + "      \"sub\": \"24400320\",\n" + "      \"upn\": \"jdoe@server.example.com\",\n" + "      \"groups\": [\"red-group\", \"green-group\", \"admin-group\", \"admin\"]\n" + "}"), new JWTOptions().setAlgorithm("RS256"));
    testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("Authorization", "Bearer " + accessTokenExp), 401, "Unauthorized", "Unauthorized");
}
Also used : PubSecKeyOptions(io.vertx.ext.auth.PubSecKeyOptions) JWT(io.vertx.ext.auth.impl.jose.JWT) JsonObject(io.vertx.core.json.JsonObject) JWTOptions(io.vertx.ext.auth.JWTOptions) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) JWK(io.vertx.ext.auth.impl.jose.JWK) Test(org.junit.Test)

Example 12 with OAuth2Options

use of io.vertx.ext.auth.oauth2.OAuth2Options in project vertx-web by vert-x3.

the class OAuth2AuthHandlerTest method testAuthCodeFlowWithScopes.

@Test
public void testAuthCodeFlowWithScopes() throws Exception {
    // lets mock an oauth2 server using code auth code flow
    OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options().setClientId("client-id").setFlow(OAuth2FlowType.AUTH_CODE).setClientSecret("client-secret").setSite("http://localhost:10000"));
    final CountDownLatch latch = new CountDownLatch(1);
    HttpServer server = vertx.createHttpServer().requestHandler(req -> {
        if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
            req.setExpectMultipart(true).bodyHandler(buffer -> req.response().putHeader("Content-Type", "application/json").end(fixture.encode()));
        } else if (req.method() == HttpMethod.POST && "/oauth/revoke".equals(req.path())) {
            req.setExpectMultipart(true).bodyHandler(buffer -> req.response().end());
        } else {
            req.response().setStatusCode(400).end();
        }
    }).listen(10000, ready -> {
        if (ready.failed()) {
            throw new RuntimeException(ready.cause());
        }
        // ready
        latch.countDown();
    });
    latch.await();
    // create a oauth2 handler on our domain to the callback: "http://localhost:8080/callback"
    OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler.create(vertx, oauth2, "http://localhost:8080/callback").withScope("read");
    // setup the callback handler for receiving the callback
    oauth2Handler.setupCallback(router.route("/callback"));
    // protect everything under /protected
    router.route("/protected/*").handler(oauth2Handler);
    // mount some handler under the protected zone
    router.route("/protected/somepage").handler(rc -> {
        assertNotNull(rc.user());
        rc.response().end("Welcome to the protected resource!");
    });
    testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> {
        // in this case we should get a redirect
        redirectURL = resp.getHeader("Location");
        assertNotNull(redirectURL);
    }, 302, "Found", null);
    // fake the redirect
    testRequest(HttpMethod.GET, "/callback?state=/protected/somepage&code=1", null, resp -> {
    }, 200, "OK", "Welcome to the protected resource!");
    server.close();
}
Also used : JWK(io.vertx.ext.auth.impl.jose.JWK) MessageDigest(java.security.MessageDigest) HttpServer(io.vertx.core.http.HttpServer) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) Router(io.vertx.ext.web.Router) Test(org.junit.Test) OAuth2FlowType(io.vertx.ext.auth.oauth2.OAuth2FlowType) AtomicReference(java.util.concurrent.atomic.AtomicReference) StandardCharsets(java.nio.charset.StandardCharsets) PubSecKeyOptions(io.vertx.ext.auth.PubSecKeyOptions) JWTOptions(io.vertx.ext.auth.JWTOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Base64(java.util.Base64) SessionStore(io.vertx.ext.web.sstore.SessionStore) HttpMethod(io.vertx.core.http.HttpMethod) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) JWT(io.vertx.ext.auth.impl.jose.JWT) WebTestBase(io.vertx.ext.web.WebTestBase) HttpServer(io.vertx.core.http.HttpServer) CountDownLatch(java.util.concurrent.CountDownLatch) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) Test(org.junit.Test)

Example 13 with OAuth2Options

use of io.vertx.ext.auth.oauth2.OAuth2Options in project vertx-web by vert-x3.

the class WebClientSessionOauth2Test method testWithAuthenticationWithoutSessionExpired.

@Test
public void testWithAuthenticationWithoutSessionExpired() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    // variation
    final AtomicInteger counter = new AtomicInteger(0);
    server = vertx.createHttpServer().requestHandler(req -> {
        if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
            if (counter.incrementAndGet() == 3) {
                fail("Should only request a token 2 times");
            } else {
                assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
                req.response().putHeader("Content-Type", "application/json").end(fixtureExpires.copy().put("calls", counter).encode());
            }
        } else if (req.method() == HttpMethod.GET && "/protected/path".equals(req.path())) {
            assertEquals("Bearer " + fixtureExpires.getString("access_token"), req.getHeader("Authorization"));
            req.response().end();
        } else {
            req.response().setStatusCode(400).end();
        }
    }).listen(8080, ready -> {
        if (ready.failed()) {
            throw new RuntimeException(ready.cause());
        }
        // ready
        latch.countDown();
    });
    awaitLatch(latch);
    OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options().setFlow(OAuth2FlowType.CLIENT).setClientId("client-id").setClientSecret("client-secret").setSite("http://localhost:8080"));
    OAuth2WebClient oauth2WebClient = OAuth2WebClient.create(webClient, oauth2);
    final CountDownLatch latchClient1 = new CountDownLatch(1);
    oauth2WebClient.withCredentials(oauthConfig);
    oauth2WebClient.get(8080, "localhost", "/protected/path").send(result -> {
        if (result.failed()) {
            fail(result.cause());
        } else {
            assertEquals(200, result.result().statusCode());
            latchClient1.countDown();
        }
    });
    // sleep so the user expires
    Thread.sleep(2000L);
    awaitLatch(latchClient1);
    final CountDownLatch latchClient2 = new CountDownLatch(1);
    // again, but this time we should not get a token
    oauth2WebClient.get(8080, "localhost", "/protected/path").send(result -> {
        if (result.failed()) {
            fail(result.cause());
        } else {
            assertEquals(200, result.result().statusCode());
            latchClient2.countDown();
        }
    });
    awaitLatch(latchClient2);
}
Also used : Oauth2Credentials(io.vertx.ext.auth.oauth2.Oauth2Credentials) Future.succeededFuture(io.vertx.core.Future.succeededFuture) AUTHORIZATION(io.vertx.core.http.HttpHeaders.AUTHORIZATION) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Future.failedFuture(io.vertx.core.Future.failedFuture) OAuth2FlowType(io.vertx.ext.auth.oauth2.OAuth2FlowType) Future(io.vertx.core.Future) Supplier(java.util.function.Supplier) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CountDownLatch(java.util.concurrent.CountDownLatch) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) Test(org.junit.Test)

Example 14 with OAuth2Options

use of io.vertx.ext.auth.oauth2.OAuth2Options in project vertx-web by vert-x3.

the class WebClientSessionOauth2Test method testWithAuthentication.

@Test
public void testWithAuthentication() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    server = vertx.createHttpServer().requestHandler(req -> {
        if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
            assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
            req.response().putHeader("Content-Type", "application/json").end(fixture.encode());
        } else if (req.method() == HttpMethod.GET && "/protected/path".equals(req.path())) {
            assertEquals("Bearer " + fixture.getString("access_token"), req.getHeader("Authorization"));
            req.response().end();
        } else {
            req.response().setStatusCode(400).end();
        }
    }).listen(8080, ready -> {
        if (ready.failed()) {
            throw new RuntimeException(ready.cause());
        }
        // ready
        latch.countDown();
    });
    awaitLatch(latch);
    OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options().setFlow(OAuth2FlowType.CLIENT).setClientId("client-id").setClientSecret("client-secret").setSite("http://localhost:8080"));
    OAuth2WebClient oauth2WebClient = OAuth2WebClient.create(WebClientSession.create(webClient), oauth2);
    final CountDownLatch latchClient = new CountDownLatch(1);
    oauth2WebClient.withCredentials(oauthConfig).get(8080, "localhost", "/protected/path").send(result -> {
        if (result.failed()) {
            fail(result.cause());
        } else {
            assertEquals(200, result.result().statusCode());
            latchClient.countDown();
        }
    });
    awaitLatch(latchClient);
}
Also used : Oauth2Credentials(io.vertx.ext.auth.oauth2.Oauth2Credentials) Future.succeededFuture(io.vertx.core.Future.succeededFuture) AUTHORIZATION(io.vertx.core.http.HttpHeaders.AUTHORIZATION) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Future.failedFuture(io.vertx.core.Future.failedFuture) OAuth2FlowType(io.vertx.ext.auth.oauth2.OAuth2FlowType) Future(io.vertx.core.Future) Supplier(java.util.function.Supplier) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) CountDownLatch(java.util.concurrent.CountDownLatch) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) Test(org.junit.Test)

Example 15 with OAuth2Options

use of io.vertx.ext.auth.oauth2.OAuth2Options in project vertx-web by vert-x3.

the class WebClientSessionOauth2Test method testWithAuthenticationWithoutSession.

@Test
public void testWithAuthenticationWithoutSession() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    server = vertx.createHttpServer().requestHandler(req -> {
        if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
            assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
            req.response().putHeader("Content-Type", "application/json").end(fixture.encode());
        } else if (req.method() == HttpMethod.GET && "/protected/path".equals(req.path())) {
            assertEquals("Bearer " + fixture.getString("access_token"), req.getHeader("Authorization"));
            req.response().end();
        } else {
            req.response().setStatusCode(400).end();
        }
    }).listen(8080, ready -> {
        if (ready.failed()) {
            throw new RuntimeException(ready.cause());
        }
        // ready
        latch.countDown();
    });
    awaitLatch(latch);
    OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options().setFlow(OAuth2FlowType.CLIENT).setClientId("client-id").setClientSecret("client-secret").setSite("http://localhost:8080"));
    OAuth2WebClient oauth2WebClient = OAuth2WebClient.create(webClient, oauth2);
    final CountDownLatch latchClient = new CountDownLatch(1);
    oauth2WebClient.withCredentials(oauthConfig).get(8080, "localhost", "/protected/path").send(result -> {
        if (result.failed()) {
            fail(result.cause());
        } else {
            assertEquals(200, result.result().statusCode());
            latchClient.countDown();
        }
    });
    awaitLatch(latchClient);
}
Also used : Oauth2Credentials(io.vertx.ext.auth.oauth2.Oauth2Credentials) Future.succeededFuture(io.vertx.core.Future.succeededFuture) AUTHORIZATION(io.vertx.core.http.HttpHeaders.AUTHORIZATION) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Future.failedFuture(io.vertx.core.Future.failedFuture) OAuth2FlowType(io.vertx.ext.auth.oauth2.OAuth2FlowType) Future(io.vertx.core.Future) Supplier(java.util.function.Supplier) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) CountDownLatch(java.util.concurrent.CountDownLatch) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) Test(org.junit.Test)

Aggregations

OAuth2Options (io.vertx.ext.auth.oauth2.OAuth2Options)22 OAuth2Auth (io.vertx.ext.auth.oauth2.OAuth2Auth)21 Test (org.junit.Test)19 JsonObject (io.vertx.core.json.JsonObject)18 OAuth2FlowType (io.vertx.ext.auth.oauth2.OAuth2FlowType)17 CountDownLatch (java.util.concurrent.CountDownLatch)17 HttpMethod (io.vertx.core.http.HttpMethod)16 JWTOptions (io.vertx.ext.auth.JWTOptions)10 Future (io.vertx.core.Future)9 Buffer (io.vertx.core.buffer.Buffer)9 PubSecKeyOptions (io.vertx.ext.auth.PubSecKeyOptions)9 JWK (io.vertx.ext.auth.impl.jose.JWK)9 JWT (io.vertx.ext.auth.impl.jose.JWT)9 SessionStore (io.vertx.ext.web.sstore.SessionStore)9 Future.failedFuture (io.vertx.core.Future.failedFuture)8 Future.succeededFuture (io.vertx.core.Future.succeededFuture)8 AUTHORIZATION (io.vertx.core.http.HttpHeaders.AUTHORIZATION)8 HttpServer (io.vertx.core.http.HttpServer)8 Oauth2Credentials (io.vertx.ext.auth.oauth2.Oauth2Credentials)8 Router (io.vertx.ext.web.Router)8