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

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

Introduction

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

Prototype

public SessionManagementConfigurer<HttpSecurity> sessionManagement() throws Exception 

Source Link

Document

Allows configuring of Session Management.

Usage

From source file:org.opendatakit.configuration.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    logger.info("Setting up authentication.");
    http.exceptionHandling().authenticationEntryPoint(delegatingAuthenticationEntryPoint());

    // We have a choice here; stateless OR enable sessions and use CSRF.
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.csrf().disable();//from w ww .  j a va 2s. c o  m

    http.authorizeRequests().antMatchers("/").permitAll();
    http.authorizeRequests().antMatchers("/healthcheck").permitAll();
    http.authorizeRequests().antMatchers("/swagger.json").permitAll();
    http.authorizeRequests().antMatchers("/favicon.ico").permitAll();
    http.authorizeRequests().antMatchers("/index.html").permitAll();
    http.authorizeRequests().antMatchers("/swagger/**").permitAll();
    http.authorizeRequests().antMatchers("/images/**").permitAll();
    http.authorizeRequests().antMatchers("/odktables/**").hasRole("SYNCHRONIZE_TABLES");
    http.authorizeRequests().antMatchers("/users/list").hasRole("USER"); // Backwards compatible
                                                                         // with aggregate
    http.authorizeRequests().antMatchers("/roles/granted").hasRole("USER"); // Backwards compatible
                                                                            // with aggregate
    http.authorizeRequests().antMatchers("/admin/**").hasRole("SITE_ACCESS_ADMIN");

    // This is where we are currently enabling a fallback to Basic Authentication.
    // We may wish to remove this, as it is not very secure. On the other hand, we're not requiring
    // anyone to use it.
    http.authorizeRequests().antMatchers("/**").authenticated().and()
            .addFilterBefore(basicAuthenticationFilter(), AnonymousAuthenticationFilter.class)
            .addFilterAt(anonymousFilter(), AnonymousAuthenticationFilter.class)
            .addFilter(digestAuthenticationFilter());

}

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

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

    http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

    http.formLogin().permitAll().loginPage("/login").loginProcessingUrl("/login").usernameParameter("username")
            .passwordParameter("password").successHandler(authSuccessHandler)
            .failureHandler(authFailureHandler);

    http.logout().logoutUrl("/logout").permitAll().logoutSuccessHandler(localLogoutSuccessHandler);

    http.sessionManagement().maximumSessions(1);

    http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/error").permitAll()
            .antMatchers("/login").permitAll().antMatchers("/redirect").permitAll()
            .antMatchers("/api/public/v1/**").permitAll().antMatchers("/api/private/v1/admin/*")
            .hasIpAddress("127.0.0.1").antMatchers("/api/admin/**").access(Constants.ADMIN_ROLE_REQUIRED)
            .anyRequest().authenticated();
}

From source file:com.github.lynxdb.server.api.http.WebSecurityConfig.java

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

    http.csrf().disable();// w w w.  j a v a 2  s.c  om

    http.antMatcher("/api/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll()
            .antMatchers(EpAggregators.ENDPOINT, EpQuery.ENDPOINT, EpSuggest.ENDPOINT)
            .hasAnyRole(User.Rank.RO_USER.name(), User.Rank.RW_USER.name(), User.Rank.ADMIN.name())
            .antMatchers(HttpMethod.POST, EpPut.ENDPOINT)
            .hasAnyRole(User.Rank.RW_USER.name(), User.Rank.ADMIN.name())
            .antMatchers(EpUser.ENDPOINT, EpVhost.ENDPOINT).hasRole(User.Rank.ADMIN.name());

    http.httpBasic().realmName("Lynx");

    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

From source file:com.isalnikov.config.SecurityConfig.java

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

    http.addFilterBefore(authorizationFilter(), UserAuthorizationFilter.class);

    http.authorizeRequests()/* w w  w  . j a v a  2  s  . co m*/

            //http://www.webremeslo.ru/html/glava10.html
            .antMatchers("/page**").permitAll()

            .antMatchers("/login").permitAll().antMatchers("/user").hasRole("USER").antMatchers("/csrf")
            .hasRole("USER").anyRequest().authenticated().and().formLogin() // default login jsp 
            //.failureUrl("/login")
            //.failureHandler((new SimpleUrlAuthenticationFailureHandler())

            .permitAll().and().logout() //default logout jsp 
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            // .deleteCookies("JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE")
            .permitAll();

    http.sessionManagement().maximumSessions(1).and().invalidSessionUrl("/login");

    //        http
    //                .headers()
    //                .frameOptions().sameOrigin()
    //                .httpStrictTransportSecurity().disable();
    //http.exceptionHandling().authenticationEntryPoint(null);
    http.headers().addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy", "default-src 'self'"))
            .addHeaderWriter(new StaticHeadersWriter("X-WebKit-CSP", "default-src 'self'"));

}

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();// w  w  w  . jav a  2  s  .  c  o m
    // Viewing any page requires authentication.
    http.authorizeRequests().anyRequest().authenticated();
    http.formLogin()
            // 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: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();/*ww w  . jav a2  s  . c om*/
    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: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);
    }// w  ww  .j a v  a 2 s  .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:org.schedoscope.metascope.config.ProductionSpringConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    MetascopeConfig config = metascopeConfig();
    if (config.getAuthenticationMethod().equalsIgnoreCase("ldap")) {
        String[] allgroups = appendRolePrefix(config.getAllowedGroups(), config.getAdminGroups());
        String[] adminGroups = appendRolePrefix(config.getAdminGroups());
        http.authorizeRequests().antMatchers("/", "/?error=cred", "/status/*", "/model", "/expired").permitAll()
                .antMatchers("/admin**").hasAnyAuthority(adminGroups).antMatchers("/admin/")
                .hasAnyAuthority(adminGroups).antMatchers("/admin/**").hasAnyAuthority(adminGroups)
                .antMatchers("/**").hasAnyAuthority(allgroups).anyRequest().authenticated().and().formLogin()
                .loginPage("/").failureUrl("/?error=cred").defaultSuccessUrl("/home").and().logout()
                .logoutSuccessUrl("/").and().rememberMe().and().exceptionHandling()
                .accessDeniedPage("/accessdenied");
    } else {//from   w  w w. j a v a2  s. com
        http.authorizeRequests().antMatchers("/", "/?error=cred", "/status/*", "/expired").permitAll()
                .antMatchers("/admin**").hasAuthority("ROLE_ADMIN").antMatchers("/admin/")
                .hasAuthority("ROLE_ADMIN").antMatchers("/admin/**").hasAuthority("ROLE_ADMIN").anyRequest()
                .authenticated().and().formLogin().loginPage("/").failureUrl("/?error=cred").and().logout()
                .logoutSuccessUrl("/").and().rememberMe().and().exceptionHandling()
                .accessDeniedPage("/accessdenied");
    }
    http.sessionManagement().maximumSessions(1).expiredUrl("/expired").sessionRegistry(sessionRegistry());
}

From source file:com.traffitruck.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    // handle content encoding
    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding("UTF-8");
    filter.setForceEncoding(true);/*from   w  ww  . j ava2  s .  c  om*/
    http.addFilterBefore(filter, CsrfFilter.class);

    http.authorizeRequests()
            .antMatchers("/css/**", "/js/**", "/images/**", "/registerUser", "/verifyPhone",
                    "/resendVerificationCode", "/registrationConfirmation", "/forgotPassword", "/resetPassword")
            .permitAll()
            .antMatchers("/newload", "/myLoads", "/deleteLoad", "/load_details/**", "/editLoad/**",
                    "/updateload")
            .hasAuthority(Role.LOAD_OWNER.name())
            .antMatchers("/truckerMenu", "/findTrucksForLoad", "/addAvailability", "/myTrucks", "/newTruck",
                    "/load_details_for_trucker/**", "/load_for_truck_by_radius", "/myAlerts", "/newAlert")
            .hasAuthority(Role.TRUCK_OWNER.name())
            .antMatchers("/loads", "/trucks", "/truckApproval", "/nonApprovedTrucks",
                    "/approval/licenseimage/**", "/truckApproval", "/load_details_json/**", "/deleteLoadAdmin",
                    "/users", "/alerts", "/allow_load_details/**")
            .hasAuthority(Role.ADMIN.name()).anyRequest().authenticated();

    http.formLogin().loginPage("/login").successHandler(successHandler()).permitAll().and().logout().permitAll()
            .deleteCookies("remember-me").logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/login?logout");
    http.rememberMe().tokenRepository(repository).userDetailsService(userDetails);

    http.sessionManagement().maximumSessions(9999).expiredUrl("/login?logout").maxSessionsPreventsLogin(false)
            .and().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).invalidSessionUrl("/login");
}

From source file:br.com.joaops.smt.configuration.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/").authenticated().antMatchers("/login/*").permitAll()
            .antMatchers("/logout/*").permitAll().antMatchers("/system/user").hasRole("SYSTEM_USER_READ")
            .antMatchers("/system/user/add").hasRole("SYSTEM_USER_ADD").antMatchers("/system/user/save")
            .hasRole("SYSTEM_USER_ADD").antMatchers("/system/user/edit/*").hasRole("SYSTEM_USER_EDIT")
            .antMatchers("/system/user/update").hasRole("SYSTEM_USER_EDIT").antMatchers("/system/user/delete/*")
            .hasRole("SYSTEM_USER_DELETE").antMatchers("/system/module").hasRole("SYSTEM_MODULE_READ")
            .antMatchers("/system/module/add").hasRole("SYSTEM_MODULE_ADD").antMatchers("/system/module/save")
            .hasRole("SYSTEM_MODULE_ADD").antMatchers("/system/module/edit/*").hasRole("SYSTEM_MODULE_EDIT")
            .antMatchers("/system/module/update").hasRole("SYSTEM_MODULE_EDIT")
            .antMatchers("/system/module/delete/*").hasRole("SYSTEM_MODULE_DELETE")
            .antMatchers("/system/permission").hasRole("SYSTEM_PERMISSION_READ")
            .antMatchers("/system/permission/add").hasRole("SYSTEM_PERMISSION_ADD")
            .antMatchers("/system/permission/save").hasRole("SYSTEM_PERMISSION_ADD")
            .antMatchers("/system/permission/edit/*").hasRole("SYSTEM_PERMISSION_EDIT")
            .antMatchers("/system/permission/update").hasRole("SYSTEM_PERMISSION_EDIT")
            .antMatchers("/system/permission/delete/*").hasRole("SYSTEM_PERMISSION_DELETE").anyRequest()
            .authenticated();//  w w  w  .  jav a2 s  .c o m

    http.formLogin().loginPage("/login").loginProcessingUrl("/login/check").failureUrl("/login/error")
            .defaultSuccessUrl("/", true).usernameParameter("username").passwordParameter("password")
            .permitAll();

    http.logout().logoutUrl("/logout").logoutSuccessUrl("/login").invalidateHttpSession(true)
            .deleteCookies("JSESSIONID");

    http.sessionManagement().maximumSessions(1).and().sessionFixation().newSession();
}