Example usage for org.springframework.security.config.http SessionCreationPolicy STATELESS

List of usage examples for org.springframework.security.config.http SessionCreationPolicy STATELESS

Introduction

In this page you can find the example usage for org.springframework.security.config.http SessionCreationPolicy STATELESS.

Prototype

SessionCreationPolicy STATELESS

To view the source code for org.springframework.security.config.http SessionCreationPolicy STATELESS.

Click Source Link

Document

Spring Security will never create an HttpSession and it will never use it to obtain the SecurityContext

Usage

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 www .ja v  a2s  .  c  o  m

    /* 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:io.syndesis.runtime.KeycloakConfiguration.java

@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
protected void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and()
            .addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
            .addFilterBefore(keycloakAuthenticationProcessingFilter(), X509AuthenticationFilter.class)
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and().authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS).permitAll().antMatchers("/api/v1/swagger.*").permitAll()
            .antMatchers("/api/v1/index.html").permitAll()
            .antMatchers(HttpMethod.GET, "/api/v1/credentials/callback").permitAll().antMatchers("/api/v1/**")
            .authenticated().antMatchers("/api/setup").authenticated().anyRequest().permitAll();

    http.csrf().disable();//from   w  ww. ja  v  a2 s.c om
}

From source file:ch.ge.ve.protopoc.config.WebSecurityConfigurer.java

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity//from   ww w. j  a  v  a 2  s .c om
            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

            // restrict access for some URLs
            .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers("/api/accounts/*").denyAll().antMatchers("/auth/login").permitAll().antMatchers("/")
            .permitAll().anyRequest().fullyAuthenticated().and()

            // JWT tokens are immune to CSRF,
            // see http://stackoverflow.com/questions/21357182/csrf-token-necessary-when-using-stateless-sessionless-authentication
            .csrf().disable();

    // Custom JWT based security filter
    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    httpSecurity.headers().cacheControl();
}

From source file:eu.freme.broker.security.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());
    AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager());
    //FilterRegistrationBean registration = new FilterRegistrationBean(authenticationFilter);
    //registration.setOrder(0);

    http.addFilterBefore(authenticationFilter, BasicAuthenticationFilter.class).addFilterBefore(
            new ManagementEndpointAuthenticationFilter(authenticationManager()),
            BasicAuthenticationFilter.class);
}

From source file:com.frequentis.maritime.mcsr.config.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    log.debug("Configuring HttpSecurity");
    log.debug("RememberMe service {}", rememberMeServices);
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and()
            .addFilterBefore(basicAuthenticationFilter(), LogoutFilter.class)
            .addFilterBefore(new SkippingFilter(keycloakPreAuthActionsFilter()), LogoutFilter.class)
            .addFilterBefore(new SkippingFilter(keycloakAuthenticationProcessingFilter()),
                    X509AuthenticationFilter.class)
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and()
            //            .addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
            //            .exceptionHandling()
            //            .accessDeniedHandler(new CustomAccessDeniedHandler())
            //            .authenticationEntryPoint(authenticationEntryPoint)
            //        .and()
            .rememberMe().rememberMeServices(rememberMeServices).rememberMeParameter("remember-me")
            .key(jHipsterProperties.getSecurity().getRememberMe().getKey()).and().formLogin()
            .loginProcessingUrl("/api/authentication").successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler).usernameParameter("j_username")
            .passwordParameter("j_password").permitAll().and().logout().logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler).deleteCookies("JSESSIONID", "CSRF-TOKEN")
            .permitAll().and().headers().frameOptions().disable().and().authorizeRequests()
            .antMatchers("/api/register").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/api/elasticsearch/**").permitAll().antMatchers("/api/activate").permitAll()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/account/reset_password/inactivateit").permitAll()
            .antMatchers("/api/account/reset_password/finish").permitAll().antMatchers("/api/profile-info")
            .permitAll().antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/websocket/**").permitAll().antMatchers("/management/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/v2/api-docs/**").permitAll()
            .antMatchers(HttpMethod.PUT, "/api/**").authenticated().antMatchers(HttpMethod.POST, "/api/**")
            .authenticated().antMatchers(HttpMethod.DELETE, "/api/**").authenticated()
            .antMatchers(HttpMethod.TRACE, "/api/**").authenticated().antMatchers(HttpMethod.HEAD, "/api/**")
            .authenticated().antMatchers(HttpMethod.PATCH, "/api/**").authenticated()
            .antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll().antMatchers(HttpMethod.GET, "/api/**")
            .permitAll().antMatchers("/swagger-resources/configuration/ui").permitAll()
            .antMatchers("/swagger-ui/index.html").permitAll().and().csrf().disable();

}

From source file:io.gravitee.management.security.config.basic.BasicSecurityConfigurerAdapter.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    final String jwtSecret = environment.getProperty("jwt.secret");
    if (jwtSecret == null || jwtSecret.isEmpty()) {
        throw new IllegalStateException("JWT secret is mandatory");
    }//from   w  w w . j a  v  a 2 s .c  o  m

    http.httpBasic().realmName("Gravitee.io Management API").and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "**").permitAll().antMatchers(HttpMethod.GET, "/user/**")
            .permitAll()
            // API requests
            .antMatchers(HttpMethod.GET, "/apis/**").permitAll().antMatchers(HttpMethod.POST, "/apis/**")
            .hasAnyAuthority("ADMIN", "API_PUBLISHER").antMatchers(HttpMethod.PUT, "/apis/**")
            .hasAnyAuthority("ADMIN", "API_PUBLISHER").antMatchers(HttpMethod.DELETE, "/apis/**")
            .hasAnyAuthority("ADMIN", "API_PUBLISHER")
            // Application requests
            .antMatchers(HttpMethod.POST, "/applications/**").hasAnyAuthority("ADMIN", "API_CONSUMER")
            .antMatchers(HttpMethod.PUT, "/applications/**").hasAnyAuthority("ADMIN", "API_CONSUMER")
            .antMatchers(HttpMethod.DELETE, "/applications/**").hasAnyAuthority("ADMIN", "API_CONSUMER")
            // Instance requests
            .antMatchers(HttpMethod.GET, "/instances/**").hasAuthority("ADMIN").anyRequest().authenticated()
            .and().csrf().disable().addFilterAfter(corsFilter(), AbstractPreAuthenticatedProcessingFilter.class)
            .addFilterBefore(new JWTAuthenticationFilter(jwtCookieGenerator, jwtSecret),
                    BasicAuthenticationFilter.class)
            .addFilterAfter(
                    new AuthenticationSuccessFilter(jwtCookieGenerator, jwtSecret,
                            environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER), environment
                                    .getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)),
                    BasicAuthenticationFilter.class);
}

From source file:it.reply.orchestrator.config.security.WebSecurityConfig.java

@Override
public void configure(HttpSecurity http) throws Exception {
    if (oidcProperties.isEnabled()) {
        http.csrf().disable();//  w w w .  ja  v a2  s .  c o  m
        http.authorizeRequests().anyRequest().fullyAuthenticated().anyRequest()
                .access("#oauth2.hasScopeMatching('openid')").and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        ResourceServerSecurityConfigurer configurer = new ResourceServerSecurityConfigurer();
        configurer.setBuilder(http);
        configurer.tokenServices(applicationContext.getBean(ResourceServerTokenServices.class));
        configurer.configure(http);

        // TODO Customize the authentication entry point in order to align the response body error
        // coming from the security filter chain to the ones coming from the REST controllers
        // see https://github.com/spring-projects/spring-security-oauth/issues/605
        // configurer.authenticationEntryPoint(new CustomAuthenticationEntryPoint());
    } else {
        super.configure(http);
    }
}

From source file:org.flowable.rest.conf.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    HttpSecurity httpSecurity = http.authenticationProvider(authenticationProvider()).sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();

    // Swagger docs
    if (isSwaggerDocsEnabled()) {
        httpSecurity.authorizeRequests().antMatchers("/docs/**").permitAll();

    } else {//from w w w .j a v a2 s  .  c  om
        httpSecurity.authorizeRequests().antMatchers("/docs/**").denyAll();

    }

    httpSecurity.authorizeRequests()
            .requestMatchers(EndpointRequest.to(InfoEndpoint.class, HealthEndpoint.class)).authenticated()
            .requestMatchers(EndpointRequest.toAnyEndpoint()).hasAnyAuthority(SecurityConstants.ACCESS_ADMIN);

    // Rest API access
    if (isVerifyRestApiPrivilege()) {
        httpSecurity.authorizeRequests().anyRequest().hasAuthority(SecurityConstants.PRIVILEGE_ACCESS_REST_API)
                .and().httpBasic();

    } else {
        httpSecurity.authorizeRequests().anyRequest().authenticated().and().httpBasic();

    }
}

From source file:org.springframework.security.config.http.AuthenticationConfigBuilder.java

public AuthenticationConfigBuilder(Element element, boolean forceAutoConfig, ParserContext pc,
        SessionCreationPolicy sessionPolicy, BeanReference requestCache, BeanReference authenticationManager,
        BeanReference sessionStrategy, BeanReference portMapper, BeanReference portResolver,
        BeanMetadataElement csrfLogoutHandler) {
    this.httpElt = element;
    this.pc = pc;
    this.requestCache = requestCache;
    autoConfig = forceAutoConfig | "true".equals(element.getAttribute(ATT_AUTO_CONFIG));
    this.allowSessionCreation = sessionPolicy != SessionCreationPolicy.NEVER
            && sessionPolicy != SessionCreationPolicy.STATELESS;
    this.portMapper = portMapper;
    this.portResolver = portResolver;
    this.csrfLogoutHandler = csrfLogoutHandler;

    createAnonymousFilter();/* ww  w.j a v a2  s.co  m*/
    createRememberMeFilter(authenticationManager);
    createBasicFilter(authenticationManager);
    createFormLoginFilter(sessionStrategy, authenticationManager);
    createOpenIDLoginFilter(sessionStrategy, authenticationManager);
    createX509Filter(authenticationManager);
    createJeeFilter(authenticationManager);
    createLogoutFilter();
    createLoginPageFilterIfNeeded();
    createUserDetailsServiceFactory();
    createExceptionTranslationFilter();

}