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

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

Introduction

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

Prototype

public ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling() throws Exception 

Source Link

Document

Allows configuring exception handling.

Usage

From source file:shiver.me.timbers.spring.security.integration.StormpathAuthenticationConfiguration.java

@Override
protected final void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/stormpath/**");
    http.csrf().disable();//  www  . j ava  2s .c  om
    http.authorizeRequests().antMatchers("/stormpath/one").access("hasRole('ONE')")
            .antMatchers("/stormpath/two").access("hasRole('TWO')").anyRequest().authenticated();
    http.formLogin().successHandler(new NoRedirectAuthenticationSuccessHandler()).loginPage("/stormpath/signIn")
            .permitAll();
    http.logout().logoutUrl("/stormpath/signOut")
            .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
    http.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
}

From source file:shiver.me.timbers.spring.security.integration.JwtAnnotationSecurityConfiguration.java

@Override
protected final void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(STATELESS);
    http.antMatcher("/jwt/**");
    http.csrf().disable();/*ww w  . j ava  2s .c o  m*/
    http.authorizeRequests().antMatchers("/jwt/one").access("hasRole('ONE')").antMatchers("/jwt/two")
            .access("hasRole('TWO')").anyRequest().authenticated();
    http.formLogin().successHandler(new NoRedirectAuthenticationSuccessHandler()).loginPage("/jwt/signIn")
            .permitAll();
    http.logout().logoutUrl("/jwt/signOut").logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
    http.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
}

From source file:shiver.me.timbers.spring.security.integration.JwtApplySecurityConfiguration.java

@Override
protected final void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(STATELESS);
    http.apply(jwt());/*from   ww  w  . j a  v a 2 s .  co  m*/
    http.antMatcher("/jwt/**");
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/jwt/one").access("hasRole('ONE')").antMatchers("/jwt/two")
            .access("hasRole('TWO')").anyRequest().authenticated();
    http.formLogin().successHandler(new NoRedirectAuthenticationSuccessHandler()).loginPage("/jwt/signIn")
            .permitAll();
    http.logout().logoutUrl("/jwt/signOut").logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
    http.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
}

From source file:com.marklogic.samplestack.mock.MockApplicationSecurity.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers(HttpMethod.GET, "/session", "/questions/**", "/tags/**").permitAll()
            .and().authorizeRequests().antMatchers(HttpMethod.POST, "/search").permitAll().and()
            .authorizeRequests().antMatchers("/questions/**", "/contributors/**").authenticated().and()
            .authorizeRequests().anyRequest().denyAll();
    http.formLogin().failureHandler(failureHandler).successHandler(successHandler).permitAll().and().logout()
            .logoutSuccessHandler(logoutSuccessHandler).permitAll();
    http.csrf().disable();//from www.ja va  2s.c  o  m
    http.exceptionHandling().authenticationEntryPoint(entryPoint)
            .accessDeniedHandler(samplestackAccessDeniedHandler);

}

From source file:com.marklogic.samplestack.security.ApplicationSecurity.java

@Override
/**//from  w w w . j  av  a2s.c o m
 * Standard practice in Spring Security is to provide
 * this implementation method for building security.  This method
 * configures the endpoints' security characteristics.
 * @param http  Security object projided by the framework.
 */
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers(HttpMethod.GET, "/session", "/questions/**", "/tags/**").permitAll()
            .and().authorizeRequests().antMatchers(HttpMethod.POST, "/search").permitAll().and()
            .authorizeRequests().antMatchers("/questions/**", "/contributors/**").authenticated().and()
            .authorizeRequests().anyRequest().denyAll();
    http.formLogin().failureHandler(failureHandler).successHandler(successHandler).permitAll().and().logout()
            .logoutSuccessHandler(logoutSuccessHandler).permitAll();
    http.csrf().disable();
    http.exceptionHandling().authenticationEntryPoint(entryPoint)
            .accessDeniedHandler(samplestackAccessDeniedHandler);

}

From source file:com.miserablemind.butter.security.WebSecurityContext.java

/**
 * Main configuration method that defines the protected pages, log in form parameters, remember me and access {@link AccessDeniedHandler}.
 *
 * @param http A {@link HttpSecurity}. It is similar to Spring Security's XML &lt;http&gt; element in the namespace configuration.
 * @throws Exception//  w w w  .j a  va 2  s  .  com
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/login", "/signup", "/error/**", "/reset-password/**",
            "/forgot-password/**", "/js/**", "/img/**", "/css/**").permitAll().anyRequest()
            .access("hasRole('ROLE_USER')");

    http.formLogin().loginPage("/login").failureUrl("/login?error=true").passwordParameter("password")
            .usernameParameter("username").loginProcessingUrl("/login-submit").defaultSuccessUrl("/");

    http.csrf().disable();

    http.logout().invalidateHttpSession(true).logoutUrl("/logout-success");

    http.rememberMe().key(this.configSystem.getRememberMeKey()).rememberMeServices(this.rememberMeServices());
    http.exceptionHandling().accessDeniedHandler(this.accessDeniedHandler);
}

From source file:com.appspot.potlachkk.config.WebSecurityConfig.java

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

    // We don't want to cache requests during login
    http.requestCache().requestCache(new NullRequestCache());

    //I am not sure if this configuration is not a "work-aroud"
    //maybe there is a simpler/more elegant solution

    //Avoid CSRF token related problems with mobile clients
    http.csrf().disable();//  w w  w.j a v a  2  s.com

    //if attempt to access protected URL without authentication
    //send the client HTTP code (instead of redirecting to login form)
    //now to login a POST to /login with password=pass1&username=user1 
    //Content-Type: application/x-www-form-urlencoded must be sent
    http.exceptionHandling().authenticationEntryPoint(JSON_AUTHENTICATION_ENTRY_POINT);

    http.formLogin().successHandler(NO_REDIRECT_SUCCESS_HANDLER).failureHandler(NO_REDIRECT_FAILURE_HANDLER)
            .permitAll().and().logout().logoutUrl("/logout").logoutSuccessHandler(JSON_LOGOUT_SUCCESS_HANDLER)
            .deleteCookies("JSESSIONID").invalidateHttpSession(true).permitAll();

    //GAE - specific localhost maintenance URL
    http.authorizeRequests().antMatchers("/_ah/**").permitAll();

    //configuration URL - should be disabled in production
    http.authorizeRequests().antMatchers("/config").permitAll();
    http.authorizeRequests().antMatchers("/delconfig").permitAll();

    //test
    http.authorizeRequests().antMatchers("/image/**").permitAll();
    //http.authorizeRequests().antMatchers("/chain/**").permitAll();
    //http.authorizeRequests().antMatchers("/gift/**").permitAll();

    http.authorizeRequests().anyRequest().authenticated();
}

From source file:org.owasp.webgoat.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry security = http
            .authorizeRequests().antMatchers("/css/**", "/images/**", "/js/**", "fonts/**", "/plugins/**")
            .permitAll().antMatchers("/servlet/AdminServlet/**").hasAnyRole("WEBGOAT_ADMIN", "SERVER_ADMIN") //
            .antMatchers("/JavaSource/**").hasRole("SERVER_ADMIN") //
            .anyRequest().hasAnyRole("WEBGOAT_USER", "WEBGOAT_ADMIN", "SERVER_ADMIN");
    security.and().formLogin().loginPage("/login").defaultSuccessUrl("/welcome.mvc", true)
            .usernameParameter("username").passwordParameter("password").permitAll();
    security.and().logout().permitAll();
    security.and().csrf().disable();/*  w  w w  . j  a v  a 2 s. co  m*/

    http.headers().cacheControl().disable();
    http.exceptionHandling().authenticationEntryPoint(new AjaxAuthenticationEntryPoint("/login"));
}

From source file:com.mysample.springbootsample.config.SecurityConfig.java

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

    // Security configuration for H2 console access
    // !!!! You MUST NOT use this configuration for PRODUCTION site !!!!
    httpSecurity.authorizeRequests().antMatchers("/console/**").permitAll();
    httpSecurity.csrf().disable();/*w  ww  .  j  a va  2 s .co  m*/
    httpSecurity.headers().frameOptions().disable();

    // static resources
    httpSecurity.authorizeRequests()
            .antMatchers("/css/**", "/js/**", "/images/**", "/resources/**", "/webjars/**").permitAll();

    httpSecurity.authorizeRequests().antMatchers("/signin").anonymous().anyRequest().authenticated().and()
            .formLogin().loginPage("/signin").loginProcessingUrl("/sign-in-process.html")
            .failureUrl("/signin?error").usernameParameter("username").passwordParameter("password")
            .defaultSuccessUrl("/admin/dashboard.html", true).and().logout().logoutSuccessUrl("/signin?logout");

    httpSecurity.exceptionHandling().accessDeniedPage("/admin/dashboard.html");
    httpSecurity.sessionManagement().invalidSessionUrl("/signin");

}

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

/**
 * Configures the protected private resources
 *
 * @param http HTTP sec object//w w  w  .java2s.co 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);
    }
}