Example usage for org.springframework.security.config.annotation.web.builders HttpSecurity addFilterAfter

List of usage examples for org.springframework.security.config.annotation.web.builders HttpSecurity addFilterAfter

Introduction

In this page you can find the example usage for org.springframework.security.config.annotation.web.builders HttpSecurity addFilterAfter.

Prototype

public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter) 

Source Link

Usage

From source file:fi.helsinki.opintoni.config.SAMLSecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();/*from   w  w w.  j a va 2  s  .c om*/

    http.addFilterAfter(samlFilter(), BasicAuthenticationFilter.class).exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint);

    http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/error").permitAll()
            .antMatchers("/saml/**").permitAll().antMatchers("/redirect").permitAll()
            .antMatchers("/api/public/v1/**").permitAll().antMatchers("/api/admin/**")
            .access(Constants.ADMIN_ROLE_REQUIRED).antMatchers("/metrics/metrics/*")
            .access(securityUtils.getWhitelistedIpAccess()).anyRequest().authenticated();
}

From source file:de.thm.arsnova.config.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint());
    http.csrf().disable();/*w  w w. j a  v a2  s  .c om*/

    if (casEnabled) {
        http.addFilter(casAuthenticationFilter());
        http.addFilter(casLogoutFilter());
    }
    if (googleEnabled) {
        http.addFilterAfter(googleFilter(), CasAuthenticationFilter.class);
    }
    if (facebookEnabled) {
        http.addFilterAfter(facebookFilter(), CasAuthenticationFilter.class);
    }
    if (twitterEnabled) {
        http.addFilterAfter(twitterFilter(), CasAuthenticationFilter.class);
    }
}

From source file:org.vaadin.spring.samples.mvp.security.config.HttpSecurityConfigurer.java

void configure(Environment env, ApplicationContext context, HttpSecurity http) throws Exception {
    // all requests are authenticated
    http.authorizeRequests().antMatchers("/VAADIN/**", "/PUSH/**", "/UIDL/**", "/login", "/login/**")
            .permitAll().antMatchers("/**").fullyAuthenticated().and()
            // Vaadin chokes if this filter is enabled, disable it!
            .csrf().disable();/*w  w w .  ja  v  a2  s.c  o  m*/

    // have UI peacefully coexist with Apache CXF web-services
    String id = env.getProperty("app.security.scheme", Scheme.BASIC.id());
    Scheme scheme = Scheme.fromValue(id);
    switch (scheme) {
    case FORM:
        http.formLogin().failureUrl("/login?error").defaultSuccessUrl("/ui").permitAll().and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
                .permitAll();
        break;
    case BASIC:
        http.httpBasic();
        break;
    case DIGEST:
        // @see http://java.dzone.com/articles/basic-and-digest
        http.httpBasic();
        http.addFilterAfter(context.getBean(DigestAuthenticationFilter.class), BasicAuthenticationFilter.class);
        break;
    }

    // TODO plumb custom HTTP 403 and 404 pages
    /* http.exceptionHandling().accessDeniedPage("/access?error"); */
}

From source file:com.epam.reportportal.auth.OAuthSecurityConfig.java

@Override
protected final void configure(HttpSecurity http) throws Exception {
    //@formatter:off
    http.antMatcher("/**").authorizeRequests()
            .antMatchers(SSO_LOGIN_PATH + "/**", "/webjars/**", "/index.html", "/epam/**", "/info", "/health")
            .permitAll().anyRequest().authenticated().and().csrf().disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    CompositeFilter authCompositeFilter = new CompositeFilter();
    List<OAuth2ClientAuthenticationProcessingFilter> additionalFilters = ImmutableList
            .<OAuth2ClientAuthenticationProcessingFilter>builder()
            .addAll(getDefaultFilters(oauth2ClientContext)).addAll(getAdditionalFilters(oauth2ClientContext))
            .build();//from   w  w  w.ja  v a 2  s .com

    /* make sure filters have correct exception handler */
    additionalFilters.forEach(filter -> filter.setAuthenticationFailureHandler(OAUTH_ERROR_HANDLER));
    authCompositeFilter.setFilters(additionalFilters);

    //install additional OAuth Authentication filters
    http.addFilterAfter(authCompositeFilter, BasicAuthenticationFilter.class);
    //@formatter:on
}

From source file:ch.wisv.areafiftylan.security.SecurityConfiguration.java

/**
 * This method is responsible for the main security configuration. The formlogin() section defines how to login.
 * POST requests should be made to /login with a username and password field. Errors are redirected to /login?error.
 * The logout section is similar.//  w  w w .  j a  v a  2 s. c o m
 * <p>
 * The last section is about permissions. Anything related to Login is accessible for everyone. Use this for
 * URL-based permissions if that's the best way. Use Method specific permissions if this is not feasible.
 * <p>
 * By default, all requests to the API should come from authenticated sources. (USER or ADMIN)
 *
 * @param http default parameter
 *
 * @throws Exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    // We use our own exception handling for unauthorized request. THis simply returns a 401 when a request
    // should have been authenticated.
    http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

    //@formatter:off
    http.formLogin().loginProcessingUrl("/login").successHandler(authenticationSuccessHandler)
            .failureHandler(authenticationFailureHandler).and().logout().logoutUrl("/logout");
    //@formatter:on

    http.csrf().
    // This is used for the Mollie webhook, so it shouldn't be protected by CSRF
            ignoringAntMatchers("/orders/status").
            // Don't require CSRF on requests with valid Tokens
            requireCsrfProtectionMatcher(csrfRequestMatcher).
            // We also ignore this for Token requests
            ignoringAntMatchers("/token").
            // Ignore the route to request a password reset, no CSRF protection is needed
            ignoringAntMatchers("/requestResetPassword");
    //@formatter:on

    // This is the filter that adds the CSRF Token to the header. CSRF is enabled by default in Spring, this just
    // copies the content to the X-CSRF-TOKEN header field.
    http.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class);

    // Add support for Token-base authentication
    http.addFilterAfter(new TokenAuthenticationFilter(authenticationTokenRepository),
            UsernamePasswordAuthenticationFilter.class);
}

From source file:com.erudika.para.security.SecurityConfig.java

/**
 * Configures the protected private resources
 *
 * @param http HTTP sec object//from  ww  w .jav a 2s .c  o m
 * @throws Exception ex
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    String[] defRoles = { "USER", "MOD", "ADMIN" };
    Map<String, String> confMap = Config.getConfigMap();
    ConfigObject c = Config.getConfig().getObject("security.protected");
    ConfigValue apiSec = Config.getConfig().getValue("security.api_security");
    boolean enableRestFilter = apiSec != null && Boolean.TRUE.equals(apiSec.unwrapped());

    for (String key : c.keySet()) {
        ConfigValue cv = c.get(key);
        ArrayList<String> patterns = new ArrayList<String>();
        ArrayList<String> roles = new ArrayList<String>();

        // if API security is disabled don't add any API related patterns
        // to the list of protected resources
        if (!"api".equals(key) || enableRestFilter) {
            for (ConfigValue configValue : (ConfigList) cv) {
                if (configValue instanceof List) {
                    for (ConfigValue role : (ConfigList) configValue) {
                        roles.add(((String) role.unwrapped()).toUpperCase());
                    }
                } else {
                    patterns.add((String) configValue.unwrapped());
                }
            }
            String[] rolz = (roles.isEmpty()) ? defRoles : roles.toArray(new String[0]);
            http.authorizeRequests().antMatchers(patterns.toArray(new String[0])).hasAnyRole(rolz);
        }
    }

    if (Config.getConfigParamUnwrapped("security.csrf_protection", true)) {
        CachedCsrfTokenRepository str = new CachedCsrfTokenRepository();
        Para.injectInto(str);

        http.csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
            private final Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
            private final RegexRequestMatcher authEndpoints = new RegexRequestMatcher("^/\\w+_auth$", null);

            public boolean matches(HttpServletRequest request) {
                boolean matches = !RestRequestMatcher.INSTANCE.matches(request)
                        && !IgnoredRequestMatcher.INSTANCE.matches(request) && !authEndpoints.matches(request)
                        && !allowedMethods.matcher(request.getMethod()).matches();
                return matches;
            }
        }).csrfTokenRepository(str);
    } else {
        http.csrf().disable();
    }

    http.sessionManagement().enableSessionUrlRewriting(false);
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    http.sessionManagement().sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
    http.exceptionHandling()
            .authenticationEntryPoint(new SimpleAuthenticationEntryPoint(confMap.get("security.signin")));
    http.exceptionHandling()
            .accessDeniedHandler(new SimpleAccessDeniedHandler(confMap.get("security.access_denied")));
    http.requestCache().requestCache(new SimpleRequestCache());
    http.logout().logoutUrl(confMap.get("security.signout"))
            .logoutSuccessUrl(confMap.get("security.signout_success"));

    SimpleAuthenticationSuccessHandler successHandler = new SimpleAuthenticationSuccessHandler();
    successHandler.setDefaultTargetUrl(confMap.get("security.signin_success"));
    successHandler.setTargetUrlParameter(confMap.get("security.returnto"));
    successHandler.setUseReferer(true);

    SimpleAuthenticationFailureHandler failureHandler = new SimpleAuthenticationFailureHandler();
    failureHandler.setDefaultFailureUrl(confMap.get("security.signin_failure"));

    SimpleRememberMeServices tbrms = new SimpleRememberMeServices(Config.APP_SECRET_KEY,
            new SimpleUserService());
    tbrms.setAlwaysRemember(true);
    tbrms.setTokenValiditySeconds(Config.SESSION_TIMEOUT_SEC.intValue());
    tbrms.setCookieName(Config.AUTH_COOKIE);
    tbrms.setParameter(Config.AUTH_COOKIE.concat("-remember-me"));
    http.rememberMe().rememberMeServices(tbrms);

    PasswordAuthFilter passwordFilter = new PasswordAuthFilter("/" + PasswordAuthFilter.PASSWORD_ACTION);
    passwordFilter.setAuthenticationManager(authenticationManager());
    passwordFilter.setAuthenticationSuccessHandler(successHandler);
    passwordFilter.setAuthenticationFailureHandler(failureHandler);
    passwordFilter.setRememberMeServices(tbrms);

    OpenIDAuthFilter openidFilter = new OpenIDAuthFilter("/" + OpenIDAuthFilter.OPENID_ACTION);
    openidFilter.setAuthenticationManager(authenticationManager());
    openidFilter.setConsumer(new OpenID4JavaConsumer(new SimpleAxFetchListFactory()));
    openidFilter.setReturnToUrlParameters(Collections.singleton(confMap.get("security.returnto")));
    openidFilter.setAuthenticationSuccessHandler(successHandler);
    openidFilter.setAuthenticationFailureHandler(failureHandler);
    openidFilter.setRememberMeServices(tbrms);

    FacebookAuthFilter facebookFilter = new FacebookAuthFilter("/" + FacebookAuthFilter.FACEBOOK_ACTION);
    facebookFilter.setAuthenticationManager(authenticationManager());
    facebookFilter.setAuthenticationSuccessHandler(successHandler);
    facebookFilter.setAuthenticationFailureHandler(failureHandler);
    facebookFilter.setRememberMeServices(tbrms);

    GoogleAuthFilter googleFilter = new GoogleAuthFilter("/" + GoogleAuthFilter.GOOGLE_ACTION);
    googleFilter.setAuthenticationManager(authenticationManager());
    googleFilter.setAuthenticationSuccessHandler(successHandler);
    googleFilter.setAuthenticationFailureHandler(failureHandler);
    googleFilter.setRememberMeServices(tbrms);

    LinkedInAuthFilter linkedinFilter = new LinkedInAuthFilter("/" + LinkedInAuthFilter.LINKEDIN_ACTION);
    linkedinFilter.setAuthenticationManager(authenticationManager());
    linkedinFilter.setAuthenticationSuccessHandler(successHandler);
    linkedinFilter.setAuthenticationFailureHandler(failureHandler);
    linkedinFilter.setRememberMeServices(tbrms);

    TwitterAuthFilter twitterFilter = new TwitterAuthFilter("/" + TwitterAuthFilter.TWITTER_ACTION);
    twitterFilter.setAuthenticationManager(authenticationManager());
    twitterFilter.setAuthenticationSuccessHandler(successHandler);
    twitterFilter.setAuthenticationFailureHandler(failureHandler);
    twitterFilter.setRememberMeServices(tbrms);

    GitHubAuthFilter githubFilter = new GitHubAuthFilter("/" + GitHubAuthFilter.GITHUB_ACTION);
    githubFilter.setAuthenticationManager(authenticationManager());
    githubFilter.setAuthenticationSuccessHandler(successHandler);
    githubFilter.setAuthenticationFailureHandler(failureHandler);
    githubFilter.setRememberMeServices(tbrms);

    http.addFilterAfter(passwordFilter, BasicAuthenticationFilter.class);
    http.addFilterAfter(openidFilter, BasicAuthenticationFilter.class);
    http.addFilterAfter(facebookFilter, BasicAuthenticationFilter.class);
    http.addFilterAfter(googleFilter, BasicAuthenticationFilter.class);
    http.addFilterAfter(linkedinFilter, BasicAuthenticationFilter.class);
    http.addFilterAfter(twitterFilter, BasicAuthenticationFilter.class);
    http.addFilterAfter(githubFilter, BasicAuthenticationFilter.class);

    if (enableRestFilter) {
        RestAuthFilter restFilter = new RestAuthFilter(new Signer());
        http.addFilterAfter(restFilter, RememberMeAuthenticationFilter.class);
    }
}

From source file:org.apache.atlas.web.security.AtlasSecurityConfig.java

protected void configure(HttpSecurity httpSecurity) throws Exception {

    //@formatter:off
    httpSecurity.authorizeRequests().anyRequest().authenticated().and().headers().disable().servletApi().and()
            .csrf().disable().sessionManagement().enableSessionUrlRewriting(false)
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS).sessionFixation().newSession().and()
            .formLogin().loginPage("/login.jsp").loginProcessingUrl("/j_spring_security_check")
            .successHandler(successHandler).failureHandler(failureHandler).usernameParameter("j_username")
            .passwordParameter("j_password").and().logout().logoutSuccessUrl("/login.jsp")
            .deleteCookies("ATLASSESSIONID").logoutUrl("/logout.html").and().httpBasic()
            .authenticationEntryPoint(getDelegatingAuthenticationEntryPoint());
    //@formatter:on

    if (configuration.getBoolean("atlas.server.ha.enabled", false)) {
        LOG.info("Atlas is in HA Mode, enabling ActiveServerFilter");
        httpSecurity.addFilterAfter(activeServerFilter, BasicAuthenticationFilter.class);
    }//from  ww  w.ja v a2s.  co  m
    httpSecurity.addFilterAfter(staleTransactionCleanupFilter, BasicAuthenticationFilter.class)
            .addFilterAfter(ssoAuthenticationFilter, BasicAuthenticationFilter.class)
            .addFilterAfter(atlasAuthenticationFilter, SecurityContextHolderAwareRequestFilter.class)
            .addFilterAfter(csrfPreventionFilter, AtlasAuthenticationFilter.class)
            .addFilterAfter(atlasAuthorizationFilter, FilterSecurityInterceptor.class);
}

From source file:org.esupportail.publisher.config.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class).exceptionHandling()
            .authenticationEntryPoint(casAuthenticationEntryPoint()).and()
            .addFilterBefore(casAuthenticationFilter(), BasicAuthenticationFilter.class)
            .addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class);

    // .and()/*from  w w w  .j av a2  s.com*/
    // .rememberMe()
    // .rememberMeServices(rememberMeServices)
    // .key(env.getProperty("jhipster.security.rememberme.key"))
    // .and()
    // .formLogin()
    // .loginProcessingUrl("/api/authentication")
    // .successHandler(ajaxAuthenticationSuccessHandler)
    // .failureHandler(ajaxAuthenticationFailureHandler)
    // .usernameParameter("j_username")
    // .passwordParameter("j_password")
    // .permitAll()

    http.headers().frameOptions().disable().authorizeRequests().antMatchers("/app/**").authenticated()
            .antMatchers("/api/register").denyAll().antMatchers("/api/activate").denyAll()
            .antMatchers("/api/authenticate").denyAll().antMatchers("/api/logs/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/api/enums/**").permitAll()
            .antMatchers("/api/conf/**").permitAll().antMatchers("/api/**")
            .hasAuthority(AuthoritiesConstants.USER).antMatchers("/metrics/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/health/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/trace/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/dump/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/shutdown/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/beans/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/configprops/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/info/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/autoconfig/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/env/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/trace/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/api-docs/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/published/**")
            .access("hasRole('" + AuthoritiesConstants.ANONYMOUS + "') and (hasIpAddress('"
                    + ipVariableHolder.getIpRange()
                    + "') or hasIpAddress('127.0.0.1/32') or hasIpAddress('::1'))")
            .antMatchers(FeedController.PRIVATE_RSS_FEED_URL_PATH + "**")
            .access("hasRole('" + AuthoritiesConstants.ANONYMOUS + "') and (hasIpAddress('"
                    + ipVariableHolder.getIpRange()
                    + "') or hasIpAddress('127.0.0.1/32') or hasIpAddress('::1'))")
            .antMatchers(PROTECTED_PATH + "**").authenticated().antMatchers("/view/**").permitAll();
    http.logout().logoutUrl("/api/logout").logoutSuccessHandler(ajaxLogoutSuccessHandler)
            .invalidateHttpSession(true).deleteCookies("JSESSIONID").permitAll();

}

From source file:org.springframework.cloud.dataflow.server.config.security.OAuthSecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {

    final RequestMatcher textHtmlMatcher = new MediaTypeRequestMatcher(
            new BrowserDetectingContentNegotiationStrategy(), MediaType.TEXT_HTML);

    final BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
    basicAuthenticationEntryPoint.setRealmName(securityProperties.getBasic().getRealm());
    basicAuthenticationEntryPoint.afterPropertiesSet();

    final Filter oauthFilter = oauthFilter();
    BasicAuthenticationFilter basicAuthenticationFilter = new BasicAuthenticationFilter(providerManager(),
            basicAuthenticationEntryPoint);

    http.addFilterAfter(oauthFilter, basicAuthenticationFilter.getClass());
    http.addFilterBefore(basicAuthenticationFilter, oauthFilter.getClass());
    http.addFilterBefore(oAuth2AuthenticationProcessingFilter(), basicAuthenticationFilter.getClass());

    http.authorizeRequests()/*from  w w w .ja  va  2s  .c o  m*/
            .antMatchers("/security/info**", "/login**", dashboard("/logout-success-oauth.html"),
                    dashboard("/styles/**"), dashboard("/images/**"), dashboard("/fonts/**"),
                    dashboard("/lib/**"))
            .permitAll().anyRequest().authenticated().and().httpBasic().and().logout()
            .logoutSuccessUrl(dashboard("/logout-success-oauth.html")).and().csrf().disable()
            .exceptionHandling()
            .defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login"), textHtmlMatcher)
            .defaultAuthenticationEntryPointFor(basicAuthenticationEntryPoint, AnyRequestMatcher.INSTANCE);

    securityStateBean.setAuthenticationEnabled(true);
    securityStateBean.setAuthorizationEnabled(false);
}