org.pac4j.core.config.Config Java Examples

The following examples show how to use org.pac4j.core.config.Config. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShiroConfiguration.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * 对过滤器进行调整
 *
 * @param securityManager
 * @return
 */
@Bean(name = "shiroFilter")
protected ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager, Config config) {
    ShiroFilterFactoryBean filterFactoryBean = super.shiroFilterFactoryBean();
    filterFactoryBean.setSecurityManager(securityManager);
    
    //过滤器设置
    Map<String, Filter> filters = new HashMap<>();
    SecurityFilter securityFilter = new SecurityFilter();
    securityFilter.setClients("cas,rest,jwt");
    securityFilter.setConfig(config);
    filters.put("casSecurityFilter", securityFilter);
    
    CallbackFilter callbackFilter = new CallbackFilter();
    callbackFilter.setConfig(config);
    filters.put("callbackFilter", callbackFilter);
    
    filterFactoryBean.setFilters(filters);
    

    return filterFactoryBean;
}
 
Example #2
Source File: SecurityFilter.java    From jee-pac4j with Apache License 2.0 6 votes vote down vote up
@Override
protected final void internalFilter(final HttpServletRequest request, final HttpServletResponse response,
                                    final FilterChain filterChain) throws IOException, ServletException {

    final Config config = getSharedConfig();

    final SessionStore<JEEContext> bestSessionStore = FindBest.sessionStore(null, config, JEESessionStore.INSTANCE);
    final HttpActionAdapter<Object, JEEContext> bestAdapter = FindBest.httpActionAdapter(null, config, JEEHttpActionAdapter.INSTANCE);
    final SecurityLogic<Object, JEEContext> bestLogic = FindBest.securityLogic(securityLogic, config, DefaultSecurityLogic.INSTANCE);

    final JEEContext context = new JEEContext(request, response, bestSessionStore);
    bestLogic.perform(context, config, (ctx, profiles, parameters) -> {
        // if no profiles are loaded, pac4j is not concerned with this request
        filterChain.doFilter(profiles.isEmpty() ? request : new Pac4JHttpServletRequestWrapper(request, profiles), response);
        return null;
    }, bestAdapter, clients, authorizers, matchers, multiProfile);
}
 
Example #3
Source File: TestConfig.java    From jax-rs-pac4j with Apache License 2.0 6 votes vote down vote up
default Config getConfig() {
    // login not used because the ajax resolver always answer true
    Authenticator<UsernamePasswordCredentials> auth = new SimpleTestUsernamePasswordAuthenticator();
    FormClient client = new FormClient("notUsedLoginUrl", auth);
    DirectFormClient client2 = new DirectFormClient(auth);
    DirectFormClient client3 = new DirectFormClient(auth);
    client3.setName(DEFAULT_CLIENT);

    Clients clients = new Clients("notUsedCallbackUrl", client, client2, client3);
    // in case of invalid credentials, we simply want the error, not a redirect to the login url
    clients.setAjaxRequestResolver(new JaxRsAjaxRequestResolver());
    
    // so that callback url have the correct prefix w.r.t. the container's context
    clients.setUrlResolver(new JaxRsUrlResolver());
    
    clients.setDefaultSecurityClients(DEFAULT_CLIENT);

    return new Config(clients);
}
 
Example #4
Source File: BundleFactoryTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyPac4jInConfig() {
    setup(App.class, "empty-pac4j.yaml");

    App app = dropwizardTestSupport.getApplication();
    ObjectMapper om = dropwizardTestSupport.getObjectMapper();
    Environment env = dropwizardTestSupport.getEnvironment();

    Config config = app.bundle.getConfig();
    assertThat(config).isNotNull();
    // this is the default url resolver!
    assertThat(config.getClients().getUrlResolver())
            .isInstanceOf(JaxRsUrlResolver.class);
    assertThat(om.findMixInClassFor(Client.class)).isNotNull();
    assertThat(env.jersey().getResourceConfig().getSingletons())
            .haveAtLeastOne(CONDSI);

    assertThat(env.getApplicationContext().getSessionHandler())
            .isInstanceOf(SessionHandler.class);
}
 
Example #5
Source File: SecurityHandler.java    From vertx-pac4j with Apache License 2.0 6 votes vote down vote up
public SecurityHandler(final Vertx vertx,
                       final SessionStore<VertxWebContext> sessionStore,
                       final Config config, final Pac4jAuthProvider authProvider,
                       final SecurityHandlerOptions options) {
    super(authProvider);
    CommonHelper.assertNotNull("vertx", vertx);
    CommonHelper.assertNotNull("sessionStore", sessionStore);
    CommonHelper.assertNotNull("config", config);
    CommonHelper.assertNotNull("config.getClients()", config.getClients());
    CommonHelper.assertNotNull("authProvider", authProvider);
    CommonHelper.assertNotNull("options", options);

    clientNames = options.getClients();
    authorizerName = options.getAuthorizers();
    matcherName = options.getMatchers();
    multiProfile = options.isMultiProfile();
    this.vertx = vertx;
    this.sessionStore = sessionStore;
    this.config = config;
}
 
Example #6
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@Test
public void clientsAndProperties() throws Exception {
    Pac4jFactory conf = getPac4jFactory("clientsandproperties-pac4j.yaml");
    Config config = conf.build();

    assertThat(config.getClients().getClients()).hasSize(2);

    Client client0 = config.getClients().getClients().get(0);
    assertThat(client0).isExactlyInstanceOf(FacebookClient.class);
    assertThat(((FacebookClient) client0).getKey()).isEqualTo("fbId");

    Client client1 = config.getClients().getClients().get(1);
    assertThat(client1).isInstanceOf(DirectBasicAuthClient.class);
    assertThat(client1.getName()).isEqualTo("DirectBasicAuthClient");
    assertThat(((DirectBasicAuthClient) client1).getAuthenticator())
            .isNotNull()
            .isInstanceOf(SimpleTestUsernamePasswordAuthenticator.class);

    assertThat(config.getAuthorizers().size()).isEqualTo(0);

    assertThat(config.getMatchers().size()).isEqualTo(0);
}
 
Example #7
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@Test
public void allOptionsClients() throws Exception {
    Pac4jFactory conf = getPac4jFactory("alloptions-pac4j.yaml");
    Config config = conf.build();

    assertThat(config).isExactlyInstanceOf(FakeConfig.class);
    final FakeConfig fakeConfig = (FakeConfig) config;
    assertThat(fakeConfig.getProperties().size()).isEqualTo(2);
    assertThat(config.getClients().getClients()).hasSize(2);

    Client client0 = config.getClients().getClients().get(0);
    assertThat(client0).isExactlyInstanceOf(FacebookClient.class);
    assertThat(((FacebookClient) client0).getKey()).isEqualTo("fbId");

    Client client1 = config.getClients().getClients().get(1);
    assertThat(client1).isInstanceOf(DirectBasicAuthClient.class);
    assertThat(client1.getName()).isEqualTo("DirectBasicAuthClient");
    assertThat(((DirectBasicAuthClient) client1).getAuthenticator())
            .isNotNull()
            .isInstanceOf(SimpleTestUsernamePasswordAuthenticator.class);

    assertThat(config.getAuthorizers().size()).isEqualTo(1);

    assertThat(config.getMatchers().size()).isEqualTo(1);
}
 
Example #8
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@Test
public void clients() throws Exception {
    Pac4jFactory conf = getPac4jFactory("clients.yaml");
    Config config = conf.build();

    assertThat(config.getClients().getClients()).hasSize(2);

    Client client = config.getClients().getClients().get(0);
    assertThat(client).isInstanceOf(DirectBasicAuthClient.class);
    assertThat(client.getName()).isEqualTo("DirectBasicAuthClient");
    assertThat(((DirectBasicAuthClient) client).getAuthenticator())
            .isNotNull()
            .isInstanceOf(SimpleTestUsernamePasswordAuthenticator.class);

    Client client1 = config.getClients().getClients().get(1);
    assertThat(client1).isInstanceOf(DirectBasicAuthClient.class);
    assertThat(client1.getName()).isEqualTo("basic");
    assertThat(((DirectBasicAuthClient) client1).getAuthenticator())
            .isNull();
}
 
Example #9
Source File: CallbackFilter.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void filter(JaxRsContext context) throws IOException {
    Config config = getConfig();

    buildLogic(config).perform(context, config, adapter(config), context.getAbsolutePath(defaultUrl, false),
            saveInSession, multiProfile, renewSession, defaultClient);
}
 
Example #10
Source File: J2EHelper.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
public static void registerCallbackFilter(Environment environment,
        Config config, ServletCallbackFilterConfiguration fConf) {

    final CallbackFilter filter = new CallbackFilter();

    filter.setDefaultUrl(fConf.getDefaultUrl());
    filter.setMultiProfile(fConf.getMultiProfile());
    filter.setRenewSession(fConf.getRenewSession());

    registerFilter(environment, config, filter, fConf.getMapping());
}
 
Example #11
Source File: SecurityFilter.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
protected SecurityLogic<Object, JaxRsContext> buildLogic(Config config) {
    if (securityLogic != null) {
        return securityLogic;
    } else if (config.getSecurityLogic() != null) {
        return config.getSecurityLogic();
    } else {
        DefaultSecurityLogic<Object, JaxRsContext> logic = new DefaultSecurityLogic<>();
        logic.setProfileManagerFactory(JaxRsProfileManager::new);
        return logic;
    }
}
 
Example #12
Source File: SecurityFilter.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void filter(JaxRsContext context) throws IOException {

    Config config = getConfig();

    // Note: basically, there is two possible outcomes:
    // either the access is granted or there was an error or a redirect!
    // For the former, we do nothing (see SecurityGrantedAccessOutcome comments)
    // For the later, we interpret the error and abort the request using jax-rs abstractions
    buildLogic(config).perform(context, config, new SecurityGrantedAccessOutcome(), adapter(config), clients,
            authorizers, matchers, multiProfile);
}
 
Example #13
Source File: J2EHelper.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
public static void registerSecurityFilter(Environment environment,
        Config config, ServletSecurityFilterConfiguration fConf) {

    final SecurityFilter filter = new SecurityFilter();

    filter.setClients(fConf.getClients());
    filter.setAuthorizers(fConf.getAuthorizers());
    filter.setMatchers(fConf.getMatchers());
    filter.setMultiProfile(fConf.getMultiProfile());

    registerFilter(environment, config, filter, fConf.getMapping());
}
 
Example #14
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void clientsProperties() throws Exception {
    Pac4jFactory conf = getPac4jFactory("clientsproperties-pac4j.yaml");
    Config config = conf.build();

    assertThat(config.getClients().getClients()).hasSize(1);

    Client client0 = config.getClients().getClients().get(0);
    assertThat(client0).isExactlyInstanceOf(FacebookClient.class);
    assertThat(((FacebookClient) client0).getKey()).isEqualTo("fbId");

    assertThat(config.getAuthorizers().size()).isEqualTo(1);

    assertThat(config.getMatchers().size()).isEqualTo(0);
}
 
Example #15
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void matchers() throws Exception {
    Pac4jFactory conf = getPac4jFactory("matchers.yaml");
    Config config = conf.build();

    assertThat(config).isNotNull();
    assertThat(config.getMatchers()).hasSize(1)
            .containsKey("excludeUserSession");
    Matcher m = config.getMatchers().values().iterator().next();
    assertThat(m).isInstanceOf(PathMatcher.class);
    assertThat(((PathMatcher) m).getExcludedPatterns().stream().map(Pattern::toString))
            .containsExactlyInAnyOrder("^/user/session$");
}
 
Example #16
Source File: FakeConfigFactory.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public Config build(Object... parameters) {
    final FakeConfig config = new FakeConfig();
    config.setProperties((Map<String, String>) parameters[0]);
    config.setAuthorizer(new IsAnonymousAuthorizer());
    config.setMatcher(new PathMatcher());
    return config;
}
 
Example #17
Source File: J2EHelper.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
private static void registerFilter(Environment environment, Config config,
        AbstractConfigFilter filter, String mapping) {

    filter.setConfigOnly(config);

    final FilterRegistration.Dynamic filterRegistration = environment
            .servlets().addFilter(filter.getClass().getName(), filter);

    filterRegistration.addMappingForUrlPatterns(
            EnumSet.of(DispatcherType.REQUEST), true, mapping);
}
 
Example #18
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultsUnset() throws Exception {
    Pac4jFactory conf = getPac4jFactory("defaults.yaml");
    Config config = conf.build();

    Clients clients = config.getClients();
    // check that it is the correct file
    assertThat(clients.getCallbackUrl()).isEqualTo("test");
    // the default settings should be used!
    assertThat(clients.getAjaxRequestResolver()).isExactlyInstanceOf(JaxRsAjaxRequestResolver.class);
    assertThat(clients.getUrlResolver()).isExactlyInstanceOf(JaxRsUrlResolver.class);
}
 
Example #19
Source File: CallbackFilter.java    From jee-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void internalFilter(final HttpServletRequest request, final HttpServletResponse response,
                                       final FilterChain chain) throws IOException, ServletException {

    final Config config = getSharedConfig();

    final SessionStore<JEEContext> bestSessionStore = FindBest.sessionStore(null, config, JEESessionStore.INSTANCE);
    final HttpActionAdapter<Object, JEEContext> bestAdapter = FindBest.httpActionAdapter(null, config, JEEHttpActionAdapter.INSTANCE);
    final CallbackLogic<Object, JEEContext> bestLogic = FindBest.callbackLogic(callbackLogic, config, DefaultCallbackLogic.INSTANCE);

    final JEEContext context = new JEEContext(request, response, bestSessionStore);
    bestLogic.perform(context, config, bestAdapter, this.defaultUrl, this.saveInSession, this.multiProfile, this.renewSession, this.defaultClient);
}
 
Example #20
Source File: CallbackFilter.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
protected CallbackLogic<Object, JaxRsContext> buildLogic(Config config) {
    if (callbackLogic != null) {
        return callbackLogic;
    } else if (config.getCallbackLogic() != null) {
        return config.getCallbackLogic();
    } else {
        DefaultCallbackLogic<Object, JaxRsContext> logic = new DefaultCallbackLogic<>();
        logic.setProfileManagerFactory(JaxRsProfileManager::new);
        return logic;
    }
}
 
Example #21
Source File: SecurityInterceptor.java    From spring-webmvc-pac4j with Apache License 2.0 5 votes vote down vote up
private static String addAuthorizers(final Config config, final Authorizer[] authorizers) {
    final int n = internalNumber.getAndAdd(1);
    final int nbAuthorizers = authorizers.length;
    final StringBuilder names = new StringBuilder("");
    for (int i = 0; i < nbAuthorizers; i++) {
        final String name = "$int_authorizer" + n + "." + i;
        config.addAuthorizer(name, authorizers[i]);
        if (i > 0) {
            names.append(",");
        }
        names.append(name);
    }
    return names.toString();
}
 
Example #22
Source File: SecurityInterceptor.java    From spring-webmvc-pac4j with Apache License 2.0 5 votes vote down vote up
private static String addMatchers(final Config config, final Matcher[] matchers) {
    final int n = internalNumber.getAndAdd(1);
    final int nbMatchers = matchers.length;
    final StringBuilder names = new StringBuilder("");
    for (int i = 0; i < nbMatchers; i++) {
        final String name = "$int_matcher" + n + "." + i;
        config.addMatcher(name, matchers[i]);
        if (i > 0) {
            names.append(",");
        }
        names.append(name);
    }
    return names.toString();
}
 
Example #23
Source File: LogoutHandler.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
/**
 * Construct based on the option values provided
 *
 * @param vertx the vertx API
 * @param sessionStore the session store
 * @param options - the options to configure this handler
 * @param config the pac4j configuration
 */
public LogoutHandler(final Vertx vertx,
                     final SessionStore<VertxWebContext> sessionStore ,
                     final LogoutHandlerOptions options, final Config config) {
    this.defaultUrl = options.getDefaultUrl();
    this.logoutUrlPattern = options.getLogoutUrlPattern();
    this.config = config;
    this.vertx = vertx;
    this.sessionStore = sessionStore;
    this.localLogout = options.isLocalLogout();
    this.destroySession = options.isDestroySession();
    this.centralLogout = options.isCentralLogout();
}
 
Example #24
Source File: CallbackHandler.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
public CallbackHandler(final Vertx vertx,
                       final SessionStore<VertxWebContext> sessionStore,
                       final Config config,
                       final CallbackHandlerOptions options) {
    this.vertx = vertx;
    this.sessionStore = sessionStore;
    this.config = config;
    this.defaultUrl = options.getDefaultUrl();
    this.saveInSession = options.getSaveInSession();
    this.multiProfile = options.getMultiProfile();
    this.renewSession = options.getRenewSession();
    this.defaultClient = options.getDefaultClient();

}
 
Example #25
Source File: Pac4jIdentityAdapter.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
    throws IOException, ServletException {

  final HttpServletRequest request = (HttpServletRequest) servletRequest;
  final HttpServletResponse response = (HttpServletResponse) servletResponse;
  final J2EContext context = new J2EContext(request, response,
      ((Config)request.getAttribute(PAC4J_CONFIG)).getSessionStore());
  final ProfileManager<CommonProfile> manager = new ProfileManager<>(context);
  final Optional<CommonProfile> optional = manager.get(true);
  if (optional.isPresent()) {
    CommonProfile profile = optional.get();
    logger.debug("User authenticated as: {}", profile);
    manager.remove(true);
    String id = null;
    if (idAttribute != null) {
      Object attribute = profile.getAttribute(idAttribute);
      if (attribute != null) {
        id = attribute.toString();
      }
      if (id == null) {
        logger.error("Invalid attribute_id: {} configured to be used as principal"
            + " falling back to default id", idAttribute);
      }
    }
    if (id == null) {
      id = profile.getId();
    }
    testIdentifier = id;
    PrimaryPrincipal pp = new PrimaryPrincipal(id);
    Subject subject = new Subject();
    subject.getPrincipals().add(pp);
    auditService.getContext().setUsername(id);
    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
    auditor.audit(Action.AUTHENTICATION, sourceUri, ResourceType.URI, ActionOutcome.SUCCESS);

    doAs(request, response, chain, subject);
  }
}
 
Example #26
Source File: Pac4jSecurityHandler.java    From pippo with Apache License 2.0 5 votes vote down vote up
public Pac4jSecurityHandler(Config config, String clients, String authorizers, String matchers, Boolean multiProfile) {
    this.config = config;
    this.clients = clients;
    this.authorizers = authorizers;
    this.matchers = matchers;
    this.multiProfile = multiProfile;
}
 
Example #27
Source File: SettingsConfigFactory.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public Config build(Object... parameters) {
    Config config = super.build(parameters);
    config.setHttpActionAdapter(PippoNopHttpActionAdapter.INSTANCE);

    return config;
}
 
Example #28
Source File: Pac4jProducer.java    From jee-pac4j with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method which produces a pac4j web context.
 *
 * @param httpServletRequest the http servlet request to be used for building the web context
 * @param httpServletResponse the http servlet response to be used for building the web context
 * @return a web context associated with the current servlet request
 */
@Produces
JEEContext getWebContext(final HttpServletRequest httpServletRequest,
                         final HttpServletResponse httpServletResponse) {
    logger.trace("Producing a pac4j web context...");
    final SessionStore<JEEContext> bestSessionStore = FindBest.sessionStore(null, Config.INSTANCE, JEESessionStore.INSTANCE);
    JEEContext jEEContext = new JEEContext(
            httpServletRequest,
            httpServletResponse,
            bestSessionStore
    );
    logger.trace("Returning a pac4j web context.");
    return jEEContext;
}
 
Example #29
Source File: LogoutFilter.java    From jee-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void internalFilter(final HttpServletRequest request, final HttpServletResponse response,
                                       final FilterChain chain) throws IOException, ServletException {

    final Config config = getSharedConfig();

    final SessionStore<JEEContext> bestSessionStore = FindBest.sessionStore(null, config, JEESessionStore.INSTANCE);
    final HttpActionAdapter<Object, JEEContext> bestAdapter = FindBest.httpActionAdapter(null, config, JEEHttpActionAdapter.INSTANCE);
    final LogoutLogic<Object, JEEContext> bestLogic = FindBest.logoutLogic(logoutLogic, config, DefaultLogoutLogic.INSTANCE);

    final JEEContext context = new JEEContext(request, response, bestSessionStore);
    bestLogic.perform(context, config, bestAdapter, this.defaultUrl, this.logoutUrlPattern, this.localLogout, this.destroySession, this.centralLogout);
}
 
Example #30
Source File: AbstractConfigFilter.java    From jee-pac4j with Apache License 2.0 5 votes vote down vote up
public void init(final FilterConfig filterConfig) throws ServletException {
    final String configFactoryParam = filterConfig.getInitParameter(Pac4jConstants.CONFIG_FACTORY);
    if (configFactoryParam != null) {
        final Config config = ConfigBuilder.build(configFactoryParam);
        setSharedConfig(config);
    }
}