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

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

Introduction

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

Prototype

public ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests()
        throws Exception 

Source Link

Document

Allows restricting access based upon the HttpServletRequest using <h2>Example Configurations</h2> The most basic example is to configure all URLs to require the role "ROLE_USER".

Usage

From source file:com.sothawo.taboo2.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    boolean requireSsl = securityProperties.isRequireSsl();
    boolean basicEnabled = securityProperties.getBasic().isEnabled();
    log.debug("configuring http, requires ssl: {}, basic authentication: {}", requireSsl, basicEnabled);
    if (requireSsl) {
        http.requiresChannel().anyRequest().requiresSecure();
    }/*from   w  w w .ja v a  2 s .  c  o m*/
    if (basicEnabled) {
        // authentication for the taboo2 service only, the app itself doesn't need use it to display it's own login
        // form.
        http.authorizeRequests().antMatchers("/taboo2/**").authenticated().anyRequest().permitAll();
    }
    http.httpBasic().realmName("taboo2");
    http.csrf().disable();
}

From source file:cn.timeoff.config.hackspring.WebSecurityConfigurerAdapter.java

/**
 * Override this method to configure the {@link HttpSecurity}.
 * Typically subclasses should not invoke this method by calling super
 * as it may override their configuration. The default configuration is:
 *
 * <pre>// w  w  w  . j a v a  2s  .  c  o m
 * http
 *     .authorizeRequests()
 *         .anyRequest().authenticated().and()
 *     .formLogin().and()
 *     .httpBasic();
 * </pre>
 *
 * @param http
 *            the {@link HttpSecurity} to modify
 * @throws Exception
 *             if an error occurs
 */
protected void configure(HttpSecurity http) throws Exception {
    logger.debug(
            "Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");

    http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
}

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

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();//  ww w  .  j av a 2  s . c  o m

    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:eu.openanalytics.shinyproxy.UISecurityConfig.java

@Override
public void apply(HttpSecurity http) throws Exception {
    if (auth.hasAuthorization()) {

        // Limit access to the app pages according to spec permissions
        for (ProxySpec spec : proxyService.getProxySpecs(null, true)) {
            if (spec.getAccessControl() == null)
                continue;

            String[] groups = spec.getAccessControl().getGroups();
            if (groups == null || groups.length == 0)
                continue;

            String[] appGroups = Arrays.stream(groups).map(s -> s.toUpperCase()).toArray(i -> new String[i]);
            http.authorizeRequests().antMatchers("/app/" + spec.getId()).hasAnyRole(appGroups);
        }/*from  w  ww. j av a  2s  .c  o  m*/

        // Limit access to the admin pages
        http.authorizeRequests().antMatchers("/admin").hasAnyRole(userService.getAdminGroups());
    }
}

From source file:com.esquema.seguridad.ApplicationSecurity.java

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

    /* Inicio//from  w  w w .  j a v  a  2s .c o m
     *********************** Manejo de sesin y autenticacin **************************************/
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
            .antMatchers("/esquema/**").fullyAuthenticated().and().httpBasic();
    //.formLogin();
    /********************** Manejo de sesin y autenticacin ***************************************
    * Fin */

    /* Inicio
     *********************** Manejo de sesin y autenticacin **************************************/
    http.authorizeRequests().antMatchers("/").permitAll().and().authorizeRequests()
            .antMatchers("/h2/**", "/H2/**").permitAll();
    http.csrf().disable();
    http.headers().frameOptions().disable();
    /********************** Manejo de sesin y autenticacin ***************************************
    * Fin */

    /* Inicio
     *********************** Hace que el request sea solo por HTTPS **************************************
    http
        .requiresChannel().antMatchers("/escribe tu ruta aqu/**").requiresSecure();
    http.csrf().disable();
    /********************** Hace que el request sea solo por HTTPS ***************************************
    * Fin */

}

From source file:net.oneandone.stool.overview.config.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    CasAuthenticationFilter filter;//w ww .  j a va2s .c o m
    CasAuthenticationEntryPoint entryPoint;

    filter = new CasAuthenticationFilter();
    filter.setAuthenticationManager(authenticationManager());
    entryPoint = new CasAuthenticationEntryPoint();
    entryPoint.setLoginUrl(session.configuration.ldapSso + "/login/");
    entryPoint.setServiceProperties(serviceProperties());
    http.csrf().disable().exceptionHandling().authenticationEntryPoint(entryPoint).and().addFilter(filter);
    if (session.configuration.ldapUrl.isEmpty()) {
        http.authorizeRequests().antMatchers("/**").hasRole("ANONYMOUS");
    } else {
        http.authorizeRequests().antMatchers("/whoami").fullyAuthenticated().antMatchers("/**")
                .hasRole("LOGIN");
    }
}

From source file:com.orange.clara.cloud.services.sandbox.config.SecurityConfiguration.java

@Override
public void configure(HttpSecurity http) throws Exception {
    String managementContextPath = managementServerProperties.getContextPath();

    // @formatter:off
    if (securityProperties.isRequireSsl()) {
        LOGGER.info("SSL enabled in springboot config, cannot access this app using http");
        http.requiresChannel().anyRequest().requiresSecure();
    }//from  w  w  w .  j av a2s  .  co  m
    if (securityProperties.isEnableCsrf()) {
        LOGGER.info("CSRF enabled in springboot config");
        http.csrf().csrfTokenRepository(csrfTokenRepository()).and().addFilterAfter(csrfHeaderFilter(),
                CsrfFilter.class);
    }
    http.authorizeRequests().antMatchers(managementContextPath + "/health", managementContextPath + "/info")
            .access("isAnonymous() or #oauth2.throwOnError(#oauth2.hasScope('" + oauth2AdminScope + "'))")
            .antMatchers(managementContextPath + "/**").access("#oauth2.hasScope('" + oauth2AdminScope + "')")
            .anyRequest().authenticated().and().formLogin().disable().logout().disable().sessionManagement()
            .sessionCreationPolicy(securityProperties.getSessions());
    // @formatter:on

}

From source file:de.chludwig.websec.saml2sp.springconfig.SamlSpringSecurityConfig.java

/**
 * Defines the web based security configuration.
 *
 * @param http// w ww . j a  v  a2  s  . c om
 *         It allows configuring web based security for specific http requests.
 * @throws Exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().authenticationEntryPoint(samlEntryPoint());
    http.csrf().disable();
    http.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class).addFilterAfter(samlFilter(),
            BasicAuthenticationFilter.class);
    http.authorizeRequests().antMatchers(PW_LOGIN_PAGE_PATH).denyAll() // don't offer local login form in SAML SSO scenario
            .antMatchers(START_PAGE_PATH).permitAll() //
            .antMatchers(ERROR_PAGE_PATH).permitAll() //
            .antMatchers("/saml/**").permitAll() //
            .antMatchers(AUTHENTICATED_PAGE_PATH).authenticated() //
            .antMatchers(ANONYMOUS_PAGE_PATH).anonymous() //
            .antMatchers(USER_ROLE_PAGE_PATH).hasAuthority(RoleId.USER_ROLE_ID.getId()) //
            .antMatchers(ADMIN_ROLE_PAGE_PATH).hasAuthority(RoleId.ADMIN_ROLE_ID.getId()) //
            .anyRequest().authenticated();
    http.logout().logoutSuccessUrl("/");
}

From source file:com.vdenotaris.spring.boot.security.saml.web.config.WebSecurityConfig.java

/**
 * Defines the web based security configuration.
 * /*  w ww  .  j  ava2 s  . c  om*/
 * @param   http It allows configuring web based security for specific http requests.
 * @throws  Exception 
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().authenticationEntryPoint(samlEntryPoint());
    http.csrf().disable();
    http.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class).addFilterAfter(samlFilter(),
            BasicAuthenticationFilter.class);
    http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/error").permitAll()
            .antMatchers("/saml/**").permitAll().anyRequest().authenticated();
    http.logout().logoutSuccessUrl("/");
}

From source file:cn.edu.zjnu.acm.judge.config.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    SimpleUrlAuthenticationSuccessHandler simpleUrlAuthenticationSuccessHandler = new JudgeAuthenticationSuccessHandler(
            "/");
    simpleUrlAuthenticationSuccessHandler.setUseReferer(false);
    simpleUrlAuthenticationSuccessHandler.setTargetUrlParameter("url");
    DefaultRedirectStrategy defaultRedirectStrategy = new DefaultRedirectStrategy();

    simpleUrlAuthenticationSuccessHandler.setRedirectStrategy(defaultRedirectStrategy);

    SimpleUrlLogoutSuccessHandler simpleUrlLogoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
    simpleUrlLogoutSuccessHandler.setUseReferer(true);

    // @formatter:off
    http.authorizeRequests().antMatchers(ckfinder.getServlet().getPath()).hasAnyRole("ADMIN").and().csrf()
            .disable().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and()
            .formLogin().loginPage("/login").usernameParameter("user_id1").passwordParameter("password1")
            .successHandler(simpleUrlAuthenticationSuccessHandler).failureHandler(failureHandler()).permitAll()
            .and().headers().cacheControl().disable().httpStrictTransportSecurity().disable().frameOptions()
            .sameOrigin().and().logout().logoutUrl("/logout")
            .logoutSuccessHandler(simpleUrlLogoutSuccessHandler).permitAll().and().rememberMe()
            .rememberMeParameter("rememberMe").tokenRepository(persistentTokenRepository).and().requestCache()
            .requestCache(new NullRequestCache()).and().servletApi();
    // @formatter:on
}