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

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

Introduction

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

Prototype

public CsrfConfigurer<HttpSecurity> csrf() throws Exception 

Source Link

Document

Adds CSRF support.

Usage

From source file:com.xiovr.unibot.config.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    //      http.authorizeRequests().antMatchers("/css/**", "/images/**, /js/**")
    //            .permitAll().anyRequest().authenticated();
    ///*from w ww. jav  a2 s .  c o  m*/
    //      http.formLogin().failureUrl("/login").loginPage("/login")
    //            .loginProcessingUrl("/login/submit")
    //            .usernameParameter("username").passwordParameter("password")
    //            .defaultSuccessUrl("/", false).permitAll();
    //      http.logout().logoutUrl("/logout").invalidateHttpSession(true)
    //            .permitAll();

    http.headers().addHeaderWriter(
            new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN));
    http.headers().xssProtection();
    http.headers().cacheControl();
    http.headers().contentTypeOptions();
    HstsHeaderWriter writer = new HstsHeaderWriter(false);
    writer.setRequestMatcher(AnyRequestMatcher.INSTANCE);
    http.headers().addHeaderWriter(writer);
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/css/**", "/images/**").permitAll().anyRequest().authenticated();
    http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/login")
            .loginProcessingUrl("/login/submit").defaultSuccessUrl("/", false).permitAll().and()
            .exceptionHandling().accessDeniedPage("/error").and().logout().permitAll();
}

From source file:scratch.cucumber.example.SecurityConfiguration.java

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

    // The http.formLogin().defaultSuccessUrl("/path/") method is required when using stateless Spring Security
    // because the session cannot be used to redirect to the page that was requested while signed out. Unfortunately
    // using this configuration method will cause our custom success handler (below) to be overridden with the
    // default success handler. So to replicate the defaultSuccessUrl("/path/") configuration we will instead
    // correctly configure and delegate to the default success handler.
    final SimpleUrlAuthenticationSuccessHandler delegate = new SimpleUrlAuthenticationSuccessHandler();
    delegate.setDefaultTargetUrl("/spring/");

    // Make Spring Security stateless. This means no session will be created by Spring Security, nor will it use any
    // previously existing session.
    http.sessionManagement().sessionCreationPolicy(STATELESS);
    // Disable the CSRF prevention because it requires the session, which of course is not available in a
    // stateless application. It also greatly complicates the requirements for the sign in POST request.
    http.csrf().disable();
    // Viewing any page requires authentication.
    http.authorizeRequests().anyRequest().authenticated();
    http.formLogin()/*from w w w .  jav a  2 s .  com*/
            // Viewing the sign in page does not require authentication.
            .loginPage("/spring/signIn").permitAll()
            // Override the sign in success handler with our stateless implementation. This will update the response
            // with any headers and cookies that are required for subsequent authenticated requests.
            .successHandler(new StatelessAuthenticationSuccessHandler(authenticationBinder, delegate));
    http.logout().logoutUrl("/spring/signOut").logoutSuccessUrl("/spring/");
    // Add our stateless authentication filter before the default sign in filter. The default sign in filter is
    // still used for the initial sign in, but if a user is authenticated we need to acknowledge this before it is
    // reached.
    http.addFilterBefore(new StatelessAuthenticationFilter(authenticationBinder, securityContextHolder),
            UsernamePasswordAuthenticationFilter.class);
}

From source file:de.interseroh.report.webconfig.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    String successfulLoginPage = env.getProperty("login.successful.page", SUCCESSFUL_LOGIN_PAGE);
    String successfulLogoutPage = env.getProperty("logout.successful.page", SUCCESSFUL_LOGOUT_PAGE);

    http.authorizeRequests().antMatchers("/", SUCCESSFUL_LOGIN_PAGE, "/resources/**", "/imprint", "/images/**") // white list of urls
            .permitAll() // allow anyone on these links
            .anyRequest().authenticated() // all other urls need a
            // authentication
            .and().formLogin() // configure the login
            .loginPage("/login") // this is the loginPage
            .failureUrl("/login?error") // redirect to this page on failure
            .defaultSuccessUrl(successfulLoginPage) // redirect to this page
            // on success
            .permitAll() // permit any user to access the login page
            .and().logout() // logout config
            .logoutUrl("/logout") // url to trigger logout
            .logoutSuccessUrl(successfulLogoutPage) // redirect to start
            // page
            .permitAll(); // allow anyone to call the logout page

    http.csrf().disable(); // TODO Why is CSRF disabled?
    http.headers().disable(); // TODO need a different solution then
    // disabling security headers.
}

From source file:org.smigo.user.authentication.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    /*//from   ww  w .j a va 2  s.  com
            HttpSessionSecurityContextRepository repository = new HttpSessionSecurityContextRepository();
            repository.setDisableUrlRewriting(false);
            http.securityContext().securityContextRepository(repository);
    */
    http.authorizeRequests().anyRequest().permitAll();

    FormLoginConfigurer<HttpSecurity> formLogin = http.formLogin();
    formLogin.loginPage("/login");
    formLogin.loginProcessingUrl("/login");
    formLogin.failureHandler(restAuthenticationFailureHandler);
    formLogin.successHandler(emptyAuthenticationSuccessHandler);

    final SpringSocialConfigurer springSocialConfigurer = new SpringSocialConfigurer();
    springSocialConfigurer.postLoginUrl("/garden-planner");
    http.apply(springSocialConfigurer);

    RememberMeConfigurer<HttpSecurity> rememberMe = http.rememberMe();
    rememberMe.userDetailsService(customUserDetailsService);
    rememberMe.tokenValiditySeconds(Integer.MAX_VALUE);
    rememberMe.tokenRepository(persistentTokenRepository());

    LogoutConfigurer<HttpSecurity> logout = http.logout();
    logout.invalidateHttpSession(true);
    logout.logoutUrl("/logout");
    logout.logoutSuccessUrl("/welcome-back");

    CsrfConfigurer<HttpSecurity> csrf = http.csrf();
    csrf.disable();

    OpenIDLoginConfigurer<HttpSecurity> openidLogin = http.openidLogin();
    openidLogin.loginPage("/login");
    openidLogin.loginProcessingUrl("/login-openid");
    openidLogin.authenticationUserDetailsService(openIdUserDetailsService);
    openidLogin.permitAll();
    openidLogin.defaultSuccessUrl("/garden-planner");
    //      openidLogin.attributeExchange("https://www.google.com/.*").attribute("axContactEmail").type("http://axschema.org/contact/email").required(true);
}

From source file:shiver.me.timbers.security.spring.StatelessWebSecurityConfigurerAdapter.java

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

    final TokenParser<T> tokenParser = tokenParser(secret);
    final XAuthTokenHttpServletBinder<T> xAuthTokenHttpServletBinder = xAuthTokenHttpServletBinder(tokenParser);
    final AuthenticationHttpServletBinder<T> authenticationHttpServletBinder = authenticationHttpServletBinder(
            xAuthTokenHttpServletBinder, authenticationConverter());
    final ExceptionMapper<ServletException> exceptionMapper = servletExceptionExceptionMapper();

    if (!customTokenParser) {
        configure((JwtTokenParser) tokenParser);
    }//from  w  w  w .  ja va2s  .  c o  m
    if (!customXAuthTokenHttpServletBinder) {
        configure(xAuthTokenHttpServletBinder);
    }

    final StatelessAuthenticationSuccessHandler statelessAuthenticationSuccessHandler = statelessAuthenticationSuccessHandler(
            authenticationHttpServletBinder, simpleUrlAuthenticationSuccessHandler(defaultSuccessUrl()),
            exceptionMapper);
    final StatelessAuthenticationFilter statelessAuthenticationFilter = statelessAuthenticationFilter(
            authenticationHttpServletBinder, exceptionMapper);

    // Make Spring Security stateless. This means no session will be created by Spring Security, nor will it use any
    // previously existing session.
    http.sessionManagement().sessionCreationPolicy(STATELESS);
    // The CSRF prevention is disabled because it requires the session, which of course is not available in a
    // stateless application. It also greatly complicates the requirements for the sign in POST request.
    http.csrf().disable();
    // Override the sign in success handler with the stateless implementation.
    http.formLogin().successHandler(statelessAuthenticationSuccessHandler);
    // Add our stateless authentication filter before the default sign in filter. The default sign in filter is
    // still used for the initial sign in, but once a user is authenticated we need to by pass it.
    http.addFilterBefore(statelessAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    configureFurther(http);
}

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

/**
 * Configures the protected private resources
 *
 * @param http HTTP sec object/*w  w  w . j av a2s  .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:olympus.portal.security.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    /*http//ww  w  . java2s.c o m
    .httpBasic()
        .authenticationEntryPoint(samlEntryPoint());*/

    http.csrf().disable()
            /*.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()*/
            .authorizeRequests().antMatchers("/", "/error", "/saml/**").permitAll().antMatchers("/login")
            .anonymous().anyRequest().authenticated().and().logout().permitAll().logoutSuccessUrl("/");

    http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
            .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class);
}

From source file:org.ambraproject.wombat.config.SpringSecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    if (runtimeConfiguration.getCasConfiguration().isPresent()) {
        http.addFilter(casAuthenticationFilter()).addFilterBefore(requestLogoutFilter(), LogoutFilter.class)
                .addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class).authorizeRequests()
                .antMatchers(USER_AUTH_INTERCEPT_PATTERN).fullyAuthenticated().and().authorizeRequests()
                .requestMatchers(new RequestMatcher() {
                    public boolean matches(HttpServletRequest request) {
                        String path = "" + request.getServletPath() + request.getPathInfo();
                        String host = "" + request.getServerName().toLowerCase();
                        return (path != null
                                && (path.contains("DesktopApertaRxiv") || host.contains("apertarxiv")));
                    }//from   ww  w . j a  v  a2 s. co  m
                }).permitAll().and().authorizeRequests().antMatchers(NEW_COMMENT_AUTH_INTERCEPT_PATTERN)
                .fullyAuthenticated().and().authorizeRequests().antMatchers(FLAG_COMMENT_AUTH_INTERCEPT_PATTERN)
                .fullyAuthenticated();

        http.exceptionHandling().authenticationEntryPoint(casAuthenticationEntryPoint());
        http.csrf().disable();
    }
}

From source file:org.kuali.coeus.sys.framework.security.SpringRestSecurity.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().regexMatchers(V1_REST_SERVICES_REGEX).hasRole(ADMIN_ROLE).and().httpBasic();
}

From source file:org.opentestsystem.ap.iat.config.SecurityConfig.java

/**
 * Defines the web based security configuration.
 *
 * @param http It allows configuring web based security for specific http requests.
 * @throws Exception/*  ww  w .  ja  v  a  2s. c o  m*/
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().authenticationEntryPoint(samlEntryPoint());
    http.csrf().disable();
    http.addFilterBefore(forwardedHeaderFilter(), ChannelProcessingFilter.class)
            .addFilterAfter(metadataGeneratorFilter(), ForwardedHeaderFilter.class)
            .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class);
    http.headers().frameOptions().sameOrigin();
    http.authorizeRequests()
            .antMatchers("/saml/**", "/manage/**/health**", "/manage/**/info**", "/assets/**", "**.js",
                    "favicon.**", "/fontawesome**", "/glyphicons**", "/api/sec/**", "/api/ivs/**",
                    "/error/403.html", "/keepalive")
            .permitAll();
    http.authorizeRequests().antMatchers("/**").hasAnyRole("ADMIN", "USER");
    http.logout().logoutSuccessUrl("/");

    http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}