Search in sources :

Example 1 with AuthProvider

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

the class Server method start.

@Override
public void start() throws Exception {
    // quick load of test data, this is a *sync* helper not intended for
    // real deployments...
    setUpInitialData("jdbc:hsqldb:mem:test?shutdown=true");
    // Create a JDBC client with a test database
    JDBCClient client = JDBCClient.createShared(vertx, new JsonObject().put("url", "jdbc:hsqldb:mem:test?shutdown=true").put("driver_class", "org.hsqldb.jdbcDriver"));
    // If you are planning NOT to build a fat jar, then use the BoneCP pool since it
    // can handle loading the jdbc driver classes from outside vert.x lib directory
    // JDBCClient client = JDBCClient.createShared(vertx, new JsonObject()
    // .put("provider_class", "io.vertx.ext.jdbc.spi.impl.BoneCPDataSourceProvider")
    // .put("jdbcUrl", "jdbc:hsqldb:mem:test?shutdown=true")
    // .put("username", "sa")
    // .put("password", ""));
    Router router = Router.router(vertx);
    // We need cookies, sessions and request bodies
    router.route().handler(CookieHandler.create());
    router.route().handler(BodyHandler.create());
    router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
    // Simple auth service which uses a JDBC data source
    AuthProvider authProvider = JDBCAuth.create(vertx, client);
    // 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));
    // Any requests to URI starting '/private/' require login
    router.route("/private/*").handler(RedirectAuthHandler.create(authProvider, "/loginpage.html"));
    // Serve the static private pages from directory 'private'
    router.route("/private/*").handler(StaticHandler.create().setCachingEnabled(false).setWebRoot("private"));
    // Handles the actual login
    router.route("/loginhandler").handler(FormLoginHandler.create(authProvider));
    // Implement logout
    router.route("/logout").handler(context -> {
        context.clearUser();
        // Redirect back to the index page
        context.response().putHeader("location", "/").setStatusCode(302).end();
    });
    // Serve the non private static pages
    router.route().handler(StaticHandler.create());
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
Also used : JDBCClient(io.vertx.ext.jdbc.JDBCClient) JsonObject(io.vertx.core.json.JsonObject) Router(io.vertx.ext.web.Router) AuthProvider(io.vertx.ext.auth.AuthProvider)

Example 2 with AuthProvider

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

the class AuthHandlerTestBase method testAuthorisation.

protected void testAuthorisation(String username, boolean fail, Set<String> authorities) throws Exception {
    if (requiresSession()) {
        router.route().handler(BodyHandler.create());
        router.route().handler(CookieHandler.create());
        SessionStore store = getSessionStore();
        router.route().handler(SessionHandler.create(store));
    }
    JsonObject authConfig = new JsonObject().put("properties_path", "classpath:login/loginusers.properties");
    AuthProvider authProvider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, authConfig);
    AuthHandler authHandler = createAuthHandler(authProvider);
    if (authorities != null) {
        authHandler.addAuthorities(authorities);
    }
    router.route().handler(rc -> {
        // we need to be logged in
        if (rc.user() == null) {
            JsonObject authInfo = new JsonObject().put("username", username).put("password", "delicious:sausages");
            authProvider.authenticate(authInfo, res -> {
                if (res.succeeded()) {
                    rc.setUser(res.result());
                    rc.next();
                } else {
                    rc.fail(res.cause());
                }
            });
        }
    });
    router.route().handler(authHandler);
    router.route().handler(rc -> rc.response().end());
    testRequest(HttpMethod.GET, "/", fail ? 403 : 200, fail ? "Forbidden" : "OK");
}
Also used : LocalSessionStore(io.vertx.ext.web.sstore.LocalSessionStore) SessionStore(io.vertx.ext.web.sstore.SessionStore) JsonObject(io.vertx.core.json.JsonObject) AuthProvider(io.vertx.ext.auth.AuthProvider)

Example 3 with AuthProvider

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

the class BasicAuthHandlerTest method testWithSessions.

@Test
public void testWithSessions() throws Exception {
    router.route().handler(BodyHandler.create());
    router.route().handler(CookieHandler.create());
    SessionStore store = new SerializingSessionStore();
    router.route().handler(SessionHandler.create(store));
    JsonObject authConfig = new JsonObject().put("properties_path", "classpath:login/loginusers.properties");
    AuthProvider authProvider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, authConfig);
    router.route().handler(UserSessionHandler.create(authProvider));
    router.route("/protected/*").handler(BasicAuthHandler.create(authProvider));
    AtomicReference<String> sessionID = new AtomicReference<>();
    AtomicInteger count = new AtomicInteger();
    Handler<RoutingContext> handler = rc -> {
        int c = count.incrementAndGet();
        assertNotNull(rc.session());
        String sessID = sessionID.get();
        if (sessID != null) {
            assertEquals(sessID, rc.session().id());
        }
        assertNotNull(rc.user());
        assertEquals("tim", rc.user().principal().getString("username"));
        if (c == 7) {
            rc.clearUser();
        }
        rc.response().end("Welcome to the protected resource!");
    };
    router.route("/protected/somepage").handler(handler);
    AtomicReference<String> sessionCookie = new AtomicReference<>();
    testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> {
        String wwwAuth = resp.headers().get("WWW-Authenticate");
        assertNotNull(wwwAuth);
        assertEquals("Basic realm=\"" + BasicAuthHandler.DEFAULT_REALM + "\"", wwwAuth);
        String setCookie = resp.headers().get("set-cookie");
        // auth failed you should not get a session cookie!!!
        assertNull(setCookie);
    }, 401, "Unauthorized", null);
    // Now try again with credentials
    testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("Authorization", "Basic dGltOmRlbGljaW91czpzYXVzYWdlcw=="), resp -> {
        String wwwAuth = resp.headers().get("WWW-Authenticate");
        assertNull(wwwAuth);
        // auth is success, we should get a cookie!!!
        String setCookie = resp.headers().get("set-cookie");
        assertNotNull(setCookie);
        sessionCookie.set(setCookie);
    }, 200, "OK", "Welcome to the protected resource!");
    // And try again a few times we should be logged in with user stored in the session
    for (int i = 0; i < 5; i++) {
        testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("cookie", sessionCookie.get()), resp -> {
            String wwwAuth = resp.headers().get("WWW-Authenticate");
            assertNull(wwwAuth);
        }, 200, "OK", "Welcome to the protected resource!");
    }
    // Now set the user to null, this effectively logs him out
    testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> {
        String wwwAuth = resp.headers().get("WWW-Authenticate");
        assertNotNull(wwwAuth);
        assertEquals("Basic realm=\"" + BasicAuthHandler.DEFAULT_REALM + "\"", wwwAuth);
    }, 401, "Unauthorized", null);
    // And login again
    testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("Authorization", "Basic dGltOmRlbGljaW91czpzYXVzYWdlcw=="), resp -> {
        String wwwAuth = resp.headers().get("WWW-Authenticate");
        assertNull(wwwAuth);
    }, 200, "OK", "Welcome to the protected resource!");
}
Also used : SessionStore(io.vertx.ext.web.sstore.SessionStore) Session(io.vertx.ext.web.Session) PRNG(io.vertx.ext.auth.PRNG) ClusterSerializable(io.vertx.core.shareddata.impl.ClusterSerializable) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SessionImpl(io.vertx.ext.web.sstore.impl.SessionImpl) Test(org.junit.Test) RoutingContext(io.vertx.ext.web.RoutingContext) Future(io.vertx.core.Future) AtomicReference(java.util.concurrent.atomic.AtomicReference) AuthProvider(io.vertx.ext.auth.AuthProvider) Buffer(io.vertx.core.buffer.Buffer) SessionStore(io.vertx.ext.web.sstore.SessionStore) ShiroAuth(io.vertx.ext.auth.shiro.ShiroAuth) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) ShiroAuthRealmType(io.vertx.ext.auth.shiro.ShiroAuthRealmType) RoutingContext(io.vertx.ext.web.RoutingContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JsonObject(io.vertx.core.json.JsonObject) AuthProvider(io.vertx.ext.auth.AuthProvider) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 4 with AuthProvider

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

the class BasicAuthHandlerTest method testLoginFail.

@Test
public void testLoginFail() throws Exception {
    String realm = "vertx-web";
    Handler<RoutingContext> handler = rc -> {
        fail("should not get here");
        rc.response().end("Welcome to the protected resource!");
    };
    JsonObject authConfig = new JsonObject().put("properties_path", "classpath:login/loginusers.properties");
    AuthProvider authProvider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, authConfig);
    router.route("/protected/*").handler(BasicAuthHandler.create(authProvider));
    router.route("/protected/somepage").handler(handler);
    testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> {
        String wwwAuth = resp.headers().get("WWW-Authenticate");
        assertNotNull(wwwAuth);
        assertEquals("Basic realm=\"" + realm + "\"", wwwAuth);
    }, 401, "Unauthorized", null);
    // Now try again with bad credentials
    testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("Authorization", "Basic dGltOn5hdXdhZ2Vz"), resp -> {
        String wwwAuth = resp.headers().get("WWW-Authenticate");
        assertNotNull(wwwAuth);
        assertEquals("Basic realm=\"" + realm + "\"", wwwAuth);
    }, 401, "Unauthorized", null);
}
Also used : Session(io.vertx.ext.web.Session) PRNG(io.vertx.ext.auth.PRNG) ClusterSerializable(io.vertx.core.shareddata.impl.ClusterSerializable) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SessionImpl(io.vertx.ext.web.sstore.impl.SessionImpl) Test(org.junit.Test) RoutingContext(io.vertx.ext.web.RoutingContext) Future(io.vertx.core.Future) AtomicReference(java.util.concurrent.atomic.AtomicReference) AuthProvider(io.vertx.ext.auth.AuthProvider) Buffer(io.vertx.core.buffer.Buffer) SessionStore(io.vertx.ext.web.sstore.SessionStore) ShiroAuth(io.vertx.ext.auth.shiro.ShiroAuth) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) ShiroAuthRealmType(io.vertx.ext.auth.shiro.ShiroAuthRealmType) RoutingContext(io.vertx.ext.web.RoutingContext) JsonObject(io.vertx.core.json.JsonObject) AuthProvider(io.vertx.ext.auth.AuthProvider) Test(org.junit.Test)

Example 5 with AuthProvider

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

the class AuthShiroExamples method example3.

public void example3(Vertx vertx) {
    JsonObject config = new JsonObject().put("properties_path", "classpath:test-auth.properties");
    AuthProvider provider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, config);
}
Also used : JsonObject(io.vertx.core.json.JsonObject) AuthProvider(io.vertx.ext.auth.AuthProvider)

Aggregations

AuthProvider (io.vertx.ext.auth.AuthProvider)17 JsonObject (io.vertx.core.json.JsonObject)15 SessionStore (io.vertx.ext.web.sstore.SessionStore)7 Test (org.junit.Test)7 HttpMethod (io.vertx.core.http.HttpMethod)5 ShiroAuth (io.vertx.ext.auth.shiro.ShiroAuth)5 RoutingContext (io.vertx.ext.web.RoutingContext)5 AsyncResult (io.vertx.core.AsyncResult)4 Future (io.vertx.core.Future)4 Handler (io.vertx.core.Handler)4 Buffer (io.vertx.core.buffer.Buffer)4 ClusterSerializable (io.vertx.core.shareddata.impl.ClusterSerializable)4 PRNG (io.vertx.ext.auth.PRNG)4 ShiroAuthRealmType (io.vertx.ext.auth.shiro.ShiroAuthRealmType)4 Router (io.vertx.ext.web.Router)4 Session (io.vertx.ext.web.Session)4 SessionImpl (io.vertx.ext.web.sstore.impl.SessionImpl)4 Map (java.util.Map)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4