Search in sources :

Example 6 with OAuth2Auth

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

the class OAuth2KeyRotationTest method testLoadJWK.

@Test
public void testLoadJWK() {
    OAuth2Auth oauth2 = GoogleAuth.create(vertx, "", "");
    oauth2.loadJWK(load -> {
        assertFalse(load.failed());
        testComplete();
    });
    await();
}
Also used : OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) Test(org.junit.Test)

Example 7 with OAuth2Auth

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

the class OAuth2Auth method createKeycloak.

/**
 * @deprecated You should use the provider helper {@link io.vertx.ext.auth.oauth2.providers.KeycloakAuth} instead.
 *
 * Create a OAuth2 auth provider
 *
 * @param vertx the Vertx instance
 * @param config  the config as exported from the admin console
 * @return the auth provider
 */
@Deprecated
static OAuth2Auth createKeycloak(Vertx vertx, OAuth2FlowType flow, JsonObject config) {
    final OAuth2ClientOptions options = new OAuth2ClientOptions();
    // keycloak conversion to oauth2 options
    if (config.containsKey("auth-server-url")) {
        options.setSite(config.getString("auth-server-url"));
    }
    if (config.containsKey("resource")) {
        options.setClientID(config.getString("resource"));
    }
    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");
    }
    if (config.containsKey("realm-public-key")) {
        options.addPubSecKey(new PubSecKeyOptions().setAlgorithm("RS256").setPublicKey(config.getString("realm-public-key")));
    }
    return new OAuth2AuthProviderImpl(vertx, flow, options);
}
Also used : PubSecKeyOptions(io.vertx.ext.auth.PubSecKeyOptions) OAuth2AuthProviderImpl(io.vertx.ext.auth.oauth2.impl.OAuth2AuthProviderImpl)

Example 8 with OAuth2Auth

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

the class KeycloakAuth method create.

/**
 * 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 OAuth2ClientOptions options = new OAuth2ClientOptions(httpClientOptions);
    // keycloak conversion to oauth2 options
    if (config.containsKey("auth-server-url")) {
        options.setSite(config.getString("auth-server-url"));
    }
    if (config.containsKey("resource")) {
        options.setClientID(config.getString("resource"));
    }
    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")));
        // we could load keys
        options.setJWTToken(true);
    }
    return OAuth2Auth.create(vertx, flow, options);
}
Also used : PubSecKeyOptions(io.vertx.ext.auth.PubSecKeyOptions) OAuth2ClientOptions(io.vertx.ext.auth.oauth2.OAuth2ClientOptions)

Example 9 with OAuth2Auth

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

the class Server method start.

@Override
public void start() throws Exception {
    // 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.
    final Router router = Router.router(vertx);
    // 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, CLIENT_ID, 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 -> {
        // we pass the client id to the template
        JsonObject data = new JsonObject().put("client_id", CLIENT_ID);
        // and now delegate to the engine to render it.
        engine.render(data, "views/index.hbs", res -> {
            if (res.succeeded()) {
                ctx.response().putHeader("Content-Type", "text/html").end(res.result());
            } else {
                ctx.fail(res.cause());
            }
        });
    });
    // The protected resource
    router.get("/protected").handler(ctx -> {
        AccessToken user = (AccessToken) ctx.user();
        // retrieve the user profile, this is a common feature but not from the official OAuth2 spec
        user.userInfo(res -> {
            if (res.failed()) {
                // request didn't succeed because the token was revoked so we
                // invalidate the token stored in the session and render the
                // index page so that the user can start the OAuth flow again
                ctx.session().destroy();
                ctx.fail(res.cause());
            } else {
                // the request succeeded, so we use the API to fetch the user's emails
                final JsonObject userInfo = res.result();
                // fetch the user emails from the github API
                // the fetch method will retrieve any resource and ensure the right
                // secure headers are passed.
                user.fetch("https://api.github.com/user/emails", res2 -> {
                    if (res2.failed()) {
                        // request didn't succeed because the token was revoked so we
                        // invalidate the token stored in the session and render the
                        // index page so that the user can start the OAuth flow again
                        ctx.session().destroy();
                        ctx.fail(res2.cause());
                    } else {
                        userInfo.put("private_emails", res2.result().jsonArray());
                        // we pass the client info to the template
                        JsonObject data = new JsonObject().put("userInfo", userInfo);
                        // and now delegate to the engine to render it.
                        engine.render(data, "views/advanced.hbs", res3 -> {
                            if (res3.succeeded()) {
                                ctx.response().putHeader("Content-Type", "text/html").end(res3.result());
                            } else {
                                ctx.fail(res3.cause());
                            }
                        });
                    }
                });
            }
        });
    });
    vertx.createHttpServer().requestHandler(router).listen(8080);
}
Also used : AccessToken(io.vertx.ext.auth.oauth2.AccessToken) Router(io.vertx.ext.web.Router) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth)

Example 10 with OAuth2Auth

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

the class WebExamples method example59.

public void example59(Vertx vertx, Router router) {
    // create an OAuth2 provider, clientID and clientSecret should be requested to Google
    OAuth2Auth authProvider = OAuth2Auth.create(vertx, OAuth2FlowType.AUTH_CODE, new OAuth2ClientOptions().setClientID("CLIENT_ID").setClientSecret("CLIENT_SECRET").setSite("https://accounts.google.com").setTokenPath("https://www.googleapis.com/oauth2/v3/token").setAuthorizationPath("/o/oauth2/auth"));
    // create a oauth2 handler on our domain: "http://localhost:8080"
    OAuth2AuthHandler oauth2 = OAuth2AuthHandler.create(authProvider, "http://localhost:8080");
    // these are the scopes
    oauth2.addAuthority("profile");
    // setup the callback handler for receiving the Google callback
    oauth2.setupCallback(router.get("/callback"));
    // 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 Google</a>"));
}
Also used : OAuth2ClientOptions(io.vertx.ext.auth.oauth2.OAuth2ClientOptions) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth)

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