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

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

Introduction

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

Prototype

SessionCreationPolicy NEVER

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

Click Source Link

Document

Spring Security will never create an HttpSession , but will use the HttpSession if it already exists

Usage

From source file:net.prasenjit.security.login.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin().and().authorizeRequests().antMatchers("/oauth/token").anonymous().anyRequest()
            .authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
}

From source file:some.test.config.OAuthConfiguration.java

/**
 * Configure scopes for specific controller/httpmethods/roles here.
 *//*from   w ww  .  j a v a2s.  c o m*/
@Override
public void configure(final HttpSecurity http) throws Exception {

    //J-
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and().requestMatchers()
            .antMatchers("/secured/**").and().authorizeRequests().antMatchers(HttpMethod.GET, "/secured/**")
            .access("#oauth2.hasScope('testscope')");
    //J+
}

From source file:org.openbaton.nfvo.security.authentication.ResourceServer.java

@Override
public void configure(HttpSecurity http) throws Exception {
    http.headers().frameOptions().disable();

    boolean enabled = Boolean.parseBoolean(enabledSt);

    // API calls/* w w w  . ja v  a2  s.c  o  m*/
    if (true) {
        log.info("Security is enabled");
        http.authorizeRequests().regexMatchers(HttpMethod.POST, "/api/v1/").access("#oauth2.hasScope('write')")
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
                .exceptionHandling();

        http.authorizeRequests().antMatchers(HttpMethod.POST, "/api/**").access("#oauth2.hasScope('write')")
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
                .exceptionHandling();
        http.authorizeRequests().regexMatchers(HttpMethod.GET, "/api/v1/vnf-packages/*/download-with-link")
                .permitAll();
    } else {
        log.warn("Security is not enabled!");
        http.authorizeRequests().anyRequest().permitAll();
    }
}

From source file:org.jasig.portlet.survey.security.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    processingFilter.setAuthenticationManager(authenticationManager());

    http.authorizeRequests().antMatchers("/v1/**").hasRole("USER").anyRequest().authenticated().and().jee()
            .j2eePreAuthenticatedProcessingFilter(processingFilter).and().sessionManagement().sessionFixation()
            .none().sessionCreationPolicy(SessionCreationPolicy.NEVER).and().csrf().disable();

}

From source file:com.netflix.genie.web.security.SecurityUtils.java

/**
 * Build the common API HTTP security./*from  w  ww  .  java2  s  . c  o  m*/
 *
 * @param http                   The http security object to use
 * @param x509UserDetailsService The x509 authentication user details service to use
 * @param actuatorEndpoint       The endpoint where the Spring Actuator sits
 * @throws Exception when there is a problem configuring HTTP errors
 */
public static void buildAPIHttpSecurity(@NotNull final HttpSecurity http,
        @NotNull final X509UserDetailsService x509UserDetailsService, @NotBlank final String actuatorEndpoint)
        throws Exception {
    // @formatter:off
    http
            //            .regexMatcher("(/api/.*)|(" + actuatorEndpoint + ")/(?!health).*")
            .regexMatcher("(/api/.*)").authorizeRequests()
            .regexMatchers(HttpMethod.DELETE, APPLICATIONS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.PATCH, APPLICATIONS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.POST, APPLICATIONS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.PUT, APPLICATIONS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.DELETE, CLUSTERS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.PATCH, CLUSTERS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.POST, CLUSTERS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.PUT, CLUSTERS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.DELETE, COMMANDS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.PATCH, COMMANDS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.POST, COMMANDS_API_REGEX).hasRole(ADMIN_ROLE)
            .regexMatchers(HttpMethod.PUT, COMMANDS_API_REGEX).hasRole(ADMIN_ROLE).anyRequest()
            .hasRole(USER_ROLE).and().x509().authenticationUserDetailsService(x509UserDetailsService).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
            //            .and()
            //                .requiresChannel().anyRequest().requiresSecure()
            .and().requestCache().requestCache(new NullRequestCache()).and().csrf().disable();
    // @formatter:on
}

From source file:com.cfitzarl.cfjwed.core.security.SecurityConfigurationContainer.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.addFilterBefore(authenticationProcessingFilter, ExceptionTranslationFilter.class)
            .addFilterAfter(csrfValidatingFilter, authenticationProcessingFilter.getClass()).exceptionHandling()
            .accessDeniedHandler(pointHandler).authenticationEntryPoint(pointHandler).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.NEVER).and().securityContext()
            .securityContextRepository(securityContextRepository).and().csrf().disable().authorizeRequests()
            .antMatchers("/api/accounts/data").permitAll().antMatchers("/api/activations/**").permitAll()
            .antMatchers("/api/health").permitAll().antMatchers("/**").fullyAuthenticated();
}

From source file:org.devgateway.toolkit.forms.FormsSecurityConfig.java

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

    // we do not allow anyonymous token. When
    // enabled this basically means any guest
    // user will have an annoymous default role
    http.anonymous().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).
    //we let Wicket create and manage sessions, so we disable
    //session creation by spring
            and().csrf().disable(); // csrf protection interferes with some wicket stuff

    // we enable http rememberMe cookie for autologin
    // http.rememberMe().key(UNIQUE_SECRET_REMEMBER_ME_KEY);

    // resolved the error Refused to display * in a frame because it set
    // 'X-Frame-Options' to 'DENY'.
    http.headers().contentTypeOptions().and().xssProtection().and().cacheControl().and()
            .httpStrictTransportSecurity().and().frameOptions().sameOrigin();

}

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

/**
 * Configures the protected private resources
 *
 * @param http HTTP sec object// ww w .  j a v a2 s. 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.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();//w  ww . j a  v a  2  s.  c  o m
    createRememberMeFilter(authenticationManager);
    createBasicFilter(authenticationManager);
    createFormLoginFilter(sessionStrategy, authenticationManager);
    createOpenIDLoginFilter(sessionStrategy, authenticationManager);
    createX509Filter(authenticationManager);
    createJeeFilter(authenticationManager);
    createLogoutFilter();
    createLoginPageFilterIfNeeded();
    createUserDetailsServiceFactory();
    createExceptionTranslationFilter();

}