Search in sources :

Example 1 with OAuth2Auth

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

the class OAuth2AuthHandlerTest method testPasswordFlow.

@Test
public void testPasswordFlow() throws Exception {
    // lets mock a oauth2 server using code auth code flow
    OAuth2Auth oauth2 = OAuth2Auth.create(vertx, OAuth2FlowType.PASSWORD, new OAuth2ClientOptions().setClientID("client-id").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 -> {
                final String queryString = buffer.toString();
                assertTrue(queryString.contains("username=paulo"));
                assertTrue(queryString.contains("password=bananas"));
                assertTrue(queryString.contains("grant_type=password"));
                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();
    AuthHandler oauth2Handler = BasicAuthHandler.create(oauth2);
    // 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", req -> req.putHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("paulo:bananas".getBytes())), res -> {
    // in this case we should get the resource
    }, 200, "OK", "Welcome to the protected resource!");
    testRequest(HttpMethod.GET, "/protected/somepage", 401, "Unauthorized");
    server.close();
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) Base64(java.util.Base64) HttpMethod(io.vertx.core.http.HttpMethod) HttpServer(io.vertx.core.http.HttpServer) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) OAuth2FlowType(io.vertx.ext.auth.oauth2.OAuth2FlowType) OAuth2ClientOptions(io.vertx.ext.auth.oauth2.OAuth2ClientOptions) WebTestBase(io.vertx.ext.web.WebTestBase) OAuth2ClientOptions(io.vertx.ext.auth.oauth2.OAuth2ClientOptions) HttpServer(io.vertx.core.http.HttpServer) CountDownLatch(java.util.concurrent.CountDownLatch) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) Test(org.junit.Test)

Example 2 with OAuth2Auth

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

the class OAuth2AuthHandlerImpl method authURI.

private String authURI(String redirectURL) {
    final JsonObject config = new JsonObject().put("state", redirectURL);
    if (host != null) {
        config.put("redirect_uri", host + callback.getPath());
    }
    if (extraParams != null) {
        config.mergeIn(extraParams);
    }
    if (scopes.size() > 0) {
        JsonArray _scopes = new JsonArray();
        // scopes are passed as an array because the auth provider has the knowledge on how to encode them
        for (String authority : scopes) {
            _scopes.add(authority);
        }
        config.put("scopes", _scopes);
    }
    return ((OAuth2Auth) authProvider).authorizeURL(config);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth)

Example 3 with OAuth2Auth

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

the class WebExamples method example62.

public void example62(Vertx vertx, Router router) {
    // To simplify the development of the web components
    // we use a Router to route all HTTP requests
    // to organize our code in a reusable way.
    // We need cookies and sessions
    router.route().handler(CookieHandler.create());
    router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
    // Simple auth service which uses a GitHub to
    // authenticate the user
    OAuth2Auth authProvider = GithubAuth.create(vertx, "YOUR PROVIDER CLIENTID", "YOUR PROVIDER CLIENT SECRET");
    // We need a user session handler too to make sure
    // the user is stored in the session between requests
    router.route().handler(UserSessionHandler.create(authProvider));
    // we now protect the resource under the path "/protected"
    router.route("/protected").handler(OAuth2AuthHandler.create(authProvider).setupCallback(router.route("/callback")).addAuthority("user:email"));
    // Entry point to the application, this will render
    // a custom template.
    router.get("/").handler(ctx -> {
        ctx.response().putHeader("Content-Type", "text/html").end("<html>\n" + "  <body>\n" + "    <p>\n" + "      Well, hello there!\n" + "    </p>\n" + "    <p>\n" + "      We're going to the protected resource, if there is no\n" + "      user in the session we will talk to the GitHub API. Ready?\n" + "      <a href=\"/protected\">Click here</a> to begin!</a>\n" + "    </p>\n" + "    <p>\n" + "      <b>If that link doesn't work</b>, remember to provide\n" + "      your own <a href=\"https://github.com/settings/applications/new\">\n" + "      Client ID</a>!\n" + "    </p>\n" + "  </body>\n" + "</html>");
    });
    // The protected resource
    router.get("/protected").handler(ctx -> {
        // at this moment your user object should contain the info
        // from the Oauth2 response, since this is a protected resource
        // as specified above in the handler config the user object is never null
        User user = ctx.user();
        // just dump it to the client for demo purposes
        ctx.response().end(user.toString());
    });
}
Also used : User(io.vertx.ext.auth.User) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth)

Example 4 with OAuth2Auth

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

the class WebExamples method example58.

public void example58(Vertx vertx, Router router) {
    // create an OAuth2 provider, clientID and clientSecret should be requested to github
    OAuth2Auth authProvider = GithubAuth.create(vertx, "CLIENT_ID", "CLIENT_SECRET");
    // create a oauth2 handler on our running server
    // the second argument is the full url to the callback as you entered in your provider management console.
    OAuth2AuthHandler oauth2 = OAuth2AuthHandler.create(authProvider, "https://myserver.com/callback");
    // setup the callback handler for receiving the GitHub callback
    oauth2.setupCallback(router.route());
    // protect everything under /protected
    router.route("/protected/*").handler(oauth2);
    // mount some handler under the protected zone
    router.route("/protected/somepage").handler(rc -> rc.response().end("Welcome to the protected resource!"));
    // welcome page
    router.get("/").handler(ctx -> ctx.response().putHeader("content-type", "text/html").end("Hello<br><a href=\"/protected/somepage\">Protected by Github</a>"));
}
Also used : OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth)

Example 5 with OAuth2Auth

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

the class OAuth2KeyRotationTest method testLoadJWK2.

@Test
@Ignore
public void testLoadJWK2() {
    JsonObject config = new JsonObject("{\n" + "  \"realm\": \"master\",\n" + "  \"auth-server-url\": \"http://localhost:8080/auth\",\n" + "  \"ssl-required\": \"external\",\n" + "  \"resource\": \"test\",\n" + "  \"credentials\": {\n" + "    \"secret\": \"b0568625-a482-45d8-af8b-27beba502ed3\"\n" + "  }\n" + "}");
    OAuth2Auth oauth2 = KeycloakAuth.create(vertx, config);
    oauth2.loadJWK(load -> {
        assertFalse(load.failed());
        testComplete();
    });
    await();
}
Also used : JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

OAuth2Auth (io.vertx.ext.auth.oauth2.OAuth2Auth)11 Test (org.junit.Test)6 JsonObject (io.vertx.core.json.JsonObject)5 OAuth2ClientOptions (io.vertx.ext.auth.oauth2.OAuth2ClientOptions)5 HttpMethod (io.vertx.core.http.HttpMethod)2 HttpServer (io.vertx.core.http.HttpServer)2 PubSecKeyOptions (io.vertx.ext.auth.PubSecKeyOptions)2 OAuth2FlowType (io.vertx.ext.auth.oauth2.OAuth2FlowType)2 WebTestBase (io.vertx.ext.web.WebTestBase)2 Base64 (java.util.Base64)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 JsonArray (io.vertx.core.json.JsonArray)1 User (io.vertx.ext.auth.User)1 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)1 OAuth2AuthProviderImpl (io.vertx.ext.auth.oauth2.impl.OAuth2AuthProviderImpl)1 OAuth2TokenImpl (io.vertx.ext.auth.oauth2.impl.OAuth2TokenImpl)1 Router (io.vertx.ext.web.Router)1 UnknownHostException (java.net.UnknownHostException)1 Ignore (org.junit.Ignore)1