Example usage for org.apache.shiro.guice.web ShiroWebModule ShiroWebModule

List of usage examples for org.apache.shiro.guice.web ShiroWebModule ShiroWebModule

Introduction

In this page you can find the example usage for org.apache.shiro.guice.web ShiroWebModule ShiroWebModule.

Prototype

public ShiroWebModule(ServletContext servletContext) 

Source Link

Usage

From source file:org.apache.aurora.scheduler.http.api.security.ApiSecurityModule.java

License:Apache License

private void doConfigureServlets() {
    install(ShiroWebModule.guiceFilterModule(ApiModule.API_PATH));
    install(new ShiroWebModule(getServletContext()) {
        @Override//from w w w .java  2 s. com
        @SuppressWarnings("unchecked")
        protected void configureShiroWeb() {
            for (Module module : shiroConfigurationModules) {
                // We can't wrap this in a PrivateModule because Guice Multibindings don't work with them
                // and we need a Set<Realm>.
                install(module);
            }

            switch (HTTP_AUTHENTICATION_MECHANISM.get()) {
            case BASIC:
                addFilterChain("/**", ShiroWebModule.NO_SESSION_CREATION,
                        config(ShiroWebModule.AUTHC_BASIC, BasicHttpAuthenticationFilter.PERMISSIVE));
                break;

            case NEGOTIATE:
                addFilterChain("/**", ShiroWebModule.NO_SESSION_CREATION,
                        Key.get(ShiroKerberosAuthenticationFilter.class));
                break;

            default:
                addError("Unrecognized HTTP authentication mechanism.");
                break;
            }
        }
    });

    bindConstant().annotatedWith(Names.named("shiro.applicationName")).to(HTTP_REALM_NAME);

    // TODO(ksweeney): Disable session cookie.
    // TODO(ksweeney): Disable RememberMe cookie.

    install(new ShiroAopModule());

    // It is important that authentication happen before authorization is attempted, otherwise
    // the authorizing interceptor will always fail.
    MethodInterceptor authenticatingInterceptor = new ShiroAuthenticatingThriftInterceptor();
    requestInjection(authenticatingInterceptor);
    bindInterceptor(Matchers.subclassesOf(AuroraSchedulerManager.Iface.class),
            AURORA_SCHEDULER_MANAGER_SERVICE.or(AURORA_ADMIN_SERVICE), authenticatingInterceptor);

    MethodInterceptor apiInterceptor = new ShiroAuthorizingParamInterceptor(THRIFT_AURORA_SCHEDULER_MANAGER);
    requestInjection(apiInterceptor);
    bindInterceptor(Matchers.subclassesOf(AuroraSchedulerManager.Iface.class), AURORA_SCHEDULER_MANAGER_SERVICE,
            apiInterceptor);

    MethodInterceptor adminInterceptor = new ShiroAuthorizingInterceptor(THRIFT_AURORA_ADMIN);
    requestInjection(adminInterceptor);
    bindInterceptor(Matchers.subclassesOf(AnnotatedAuroraAdmin.class), AURORA_ADMIN_SERVICE, adminInterceptor);
}

From source file:org.apache.aurora.scheduler.http.api.security.HttpSecurityModule.java

License:Apache License

private void doConfigureServlets() {
    bind(Subject.class).toProvider(SecurityUtils::getSubject).in(RequestScoped.class);
    install(new AbstractModule() {
        @Override/*www . jav a  2  s  .c  o m*/
        protected void configure() {
            // Provides-only module to provide Optional<Subject>.
            // TODO(ksweeney): Use an OptionalBinder here once we're on Guice 4.0.
        }

        @Provides
        Optional<Subject> provideOptionalSubject(Subject subject) {
            return Optional.of(subject);
        }
    });
    install(guiceFilterModule(API_PATH));
    install(guiceFilterModule(H2_PATH));
    install(guiceFilterModule(H2_PATH + "/*"));
    install(new ShiroWebModule(getServletContext()) {

        // Replace the ServletContainerSessionManager which causes subject.runAs(...) in a
        // downstream user-defined filter to fail. See also: SHIRO-554
        @Override
        protected void bindSessionManager(AnnotatedBindingBuilder<SessionManager> bind) {
            bind.to(DefaultSessionManager.class).asEagerSingleton();
        }

        @Override
        @SuppressWarnings("unchecked")
        protected void configureShiroWeb() {
            for (Module module : shiroConfigurationModules) {
                // We can't wrap this in a PrivateModule because Guice Multibindings don't work with them
                // and we need a Set<Realm>.
                install(module);
            }

            // Filter registration order is important here and is defined by the matching pattern:
            // more specific pattern first.
            switch (mechanism) {
            case BASIC:
                addFilterChain(H2_PATTERN, NO_SESSION_CREATION, AUTHC_BASIC, config(PERMS, H2_PERM));
                addFilterChainWithAfterAuthFilter(config(AUTHC_BASIC, PERMISSIVE));
                break;

            case NEGOTIATE:
                addFilterChain(H2_PATTERN, NO_SESSION_CREATION, K_STRICT, config(PERMS, H2_PERM));
                addFilterChainWithAfterAuthFilter(K_PERMISSIVE);
                break;

            default:
                addError("Unrecognized HTTP authentication mechanism: " + mechanism);
                break;
            }
        }

        private void addFilterChainWithAfterAuthFilter(Key<? extends Filter> filter) {
            if (shiroAfterAuthFilterKey.isPresent()) {
                addFilterChain(filter, shiroAfterAuthFilterKey.get());
            } else {
                addFilterChain(filter);
            }
        }

        @SuppressWarnings("unchecked")
        private void addFilterChain(Key<? extends Filter> filter) {
            addFilterChain(ALL_PATTERN, NO_SESSION_CREATION, filter);
        }

        @SuppressWarnings("unchecked")
        private void addFilterChain(Key<? extends Filter> filter1, Key<? extends Filter> filter2) {
            addFilterChain(ALL_PATTERN, NO_SESSION_CREATION, filter1, filter2);
        }
    });

    bindConstant().annotatedWith(Names.named("shiro.applicationName")).to(HTTP_REALM_NAME);

    // TODO(ksweeney): Disable session cookie.
    // TODO(ksweeney): Disable RememberMe cookie.

    install(new ShiroAopModule());

    // It is important that authentication happen before authorization is attempted, otherwise
    // the authorizing interceptor will always fail.
    MethodInterceptor authenticatingInterceptor = new ShiroAuthenticatingThriftInterceptor();
    requestInjection(authenticatingInterceptor);
    bindInterceptor(Matchers.subclassesOf(AuroraSchedulerManager.Iface.class),
            AURORA_SCHEDULER_MANAGER_SERVICE.or(AURORA_ADMIN_SERVICE), authenticatingInterceptor);

    MethodInterceptor apiInterceptor = new ShiroAuthorizingParamInterceptor();
    requestInjection(apiInterceptor);
    bindInterceptor(Matchers.subclassesOf(AuroraSchedulerManager.Iface.class), AURORA_SCHEDULER_MANAGER_SERVICE,
            apiInterceptor);

    MethodInterceptor adminInterceptor = new ShiroAuthorizingInterceptor(THRIFT_AURORA_ADMIN);
    requestInjection(adminInterceptor);
    bindInterceptor(Matchers.subclassesOf(AnnotatedAuroraAdmin.class), AURORA_ADMIN_SERVICE, adminInterceptor);
}

From source file:org.lbogdanov.poker.web.AppInitializer.java

License:Apache License

/**
 * {@inheritDoc}//  ww  w.j  a v a2  s  .c om
 */
@Override
protected Injector getInjector() {
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    try {
        InputStream settings = Resources.newInputStreamSupplier(Resources.getResource("settings.properties"))
                .getInput();
        Properties props = new Properties();
        try {
            props.load(settings);
        } finally {
            settings.close();
        }
        Settings.init(Maps.fromProperties(props));
    } catch (IOException ioe) {
        throw Throwables.propagate(ioe);
    }
    final boolean isDevel = DEVELOPMENT_MODE.asBool().or(false);
    Module shiroModule = new ShiroWebModule(servletContext) {

        @Override
        @SuppressWarnings("unchecked")
        protected void configureShiroWeb() {
            bind(String.class).annotatedWith(Names.named(InjectableOAuthFilter.FAILURE_URL_PARAM))
                    .toInstance("/");
            // TODO simple ini-based realm for development
            bindRealm().toInstance(new IniRealm(IniFactorySupport.loadDefaultClassPathIni()));
            bindRealm().to(InjectableOAuthRealm.class).in(Singleton.class);

            addFilterChain("/" + Constants.OAUTH_CLBK_FILTER_URL, Key.get(InjectableOAuthFilter.class));
            addFilterChain("/" + Constants.OAUTH_FILTER_URL,
                    config(CallbackUrlSetterFilter.class, Constants.OAUTH_CLBK_FILTER_URL),
                    Key.get(InjectableOAuthUserFilter.class));
        }

        @Provides
        @Singleton
        private OAuthProvider getOAuthProvider() {
            Google2Provider provider = new Google2Provider();
            provider.setKey(GOOGLE_OAUTH_KEY.asString().get());
            provider.setSecret(GOOGLE_OAUTH_SECRET.asString().get());
            provider.setCallbackUrl("example.com"); // fake URL, will be replaced by CallbackUrlSetterFilter
            provider.setScope(Google2Scope.EMAIL_AND_PROFILE);
            return provider;
        }

    };
    Module appModule = new ServletModule() {

        @Override
        protected void configureServlets() {
            ServerConfig dbConfig = new ServerConfig();
            String jndiDataSource = DB_DATA_SOURCE.asString().orNull();
            if (Strings.isNullOrEmpty(jndiDataSource)) { // use direct JDBC connection
                DataSourceConfig dsConfig = new DataSourceConfig();
                dsConfig.setDriver(DB_DRIVER.asString().get());
                dsConfig.setUrl(DB_URL.asString().get());
                dsConfig.setUsername(DB_USER.asString().orNull());
                dsConfig.setPassword(DB_PASSWORD.asString().orNull());
                dbConfig.setDataSourceConfig(dsConfig);
            } else {
                dbConfig.setDataSourceJndiName(jndiDataSource);
            }
            dbConfig.setName("PlanningPoker");
            dbConfig.setDefaultServer(true);
            dbConfig.addClass(Session.class);
            dbConfig.addClass(User.class);

            bind(EbeanServer.class).toInstance(EbeanServerFactory.create(dbConfig));
            bind(SessionService.class).to(SessionServiceImpl.class);
            bind(UserService.class).to(UserServiceImpl.class);
            bind(WebApplication.class).to(PokerWebApplication.class);
            bind(MeteorServlet.class).in(Singleton.class);
            bind(ObjectMapper.class).toProvider(new Provider<ObjectMapper>() {

                @Override
                public ObjectMapper get() {
                    SimpleModule module = new SimpleModule().addSerializer(UserSerializer.get());
                    return new ObjectMapper().registerModule(module);
                }

            }).in(Singleton.class);
            String wicketConfig = (isDevel ? RuntimeConfigurationType.DEVELOPMENT
                    : RuntimeConfigurationType.DEPLOYMENT).toString();
            ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
            params.put(ApplicationConfig.FILTER_CLASS, WicketFilter.class.getName())
                    .put(ApplicationConfig.PROPERTY_SESSION_SUPPORT, Boolean.TRUE.toString())
                    .put(ApplicationConfig.BROADCAST_FILTER_CLASSES, TrackMessageSizeFilter.class.getName())
                    .put(ApplicationConfig.BROADCASTER_CACHE, UUIDBroadcasterCache.class.getName())
                    .put(ApplicationConfig.SHOW_SUPPORT_MESSAGE, Boolean.FALSE.toString())
                    .put(WicketFilter.FILTER_MAPPING_PARAM, "/*")
                    .put(WebApplication.CONFIGURATION, wicketConfig)
                    .put(WicketFilter.APP_FACT_PARAM, GuiceWebApplicationFactory.class.getName())
                    .put("injectorContextAttribute", Injector.class.getName()).build();
            serve("/*").with(MeteorServlet.class, params.build());
        }

    };
    Stage stage = isDevel ? Stage.DEVELOPMENT : Stage.PRODUCTION;
    return Guice.createInjector(stage, ShiroWebModule.guiceFilterModule(), shiroModule, appModule);
}

From source file:uk.co.q3c.v7.base.shiro.ShiroIntegrationTestBase.java

License:Apache License

@ModuleProvider
protected ShiroWebModule webModule() {
    return new ShiroWebModule(servletContext) {

        @Override/*from  www .  jav  a2  s  . co  m*/
        protected void configureShiroWeb() {
            bind(Realm.class).to(DefaultRealm.class);
            expose(Realm.class);
            bindRealm().to(Realm.class);

        }

    };
}