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.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();// w  w w  .j av  a 2 s .com
    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:com.wiiyaya.consumer.web.initializer.config.SecurityConfig.java

private void configResourceAuthority(HttpSecurity http) throws Exception {
    String[] noNeedAuths = resourceService.getNoNeedAuthResources();
    http.authorizeRequests().antMatchers(noNeedAuths).permitAll();

    Map<String, String[]> needAuths = resourceService.getNeedAuthResources();
    for (Map.Entry<String, String[]> entity : needAuths.entrySet()) {
        http.authorizeRequests().antMatchers(entity.getKey()).hasAnyAuthority(entity.getValue());
    }/*from w  ww.j a v  a 2  s.  c om*/

    http.authorizeRequests().anyRequest().authenticated();
}

From source file:com.alehuo.wepas2016projekti.configuration.ProductionSecurityConfiguration.java

/**
 * Konfiguroi Spring Security -lisosan//from w ww. j  ava  2 s.  c o  m
 *
 * @param http
 * @throws Exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().frameOptions().sameOrigin();
    //Sallitaan psy resurssikansioihin
    //Kirjautumislokame lytyy GET -reitist /login
    http.authorizeRequests().antMatchers("/delete/**").hasAuthority(Role.ADMINISTRATOR.toString())
            .antMatchers("/js/**", "/css/**", "/manifest.json", "/resources/**", "/register", "/fi_FI.png",
                    "/en_EN.png", "/login**", "/fonts/roboto/**")
            .permitAll().anyRequest().permitAll().anyRequest().authenticated().and().formLogin()
            .defaultSuccessUrl("/", true).loginPage("/login").permitAll().and().logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll();

}

From source file:com.econcept.init.SecurityConfig.java

@Override
protected void configure(HttpSecurity pHttpSecurity) throws Exception {
    try {//from ww  w. java 2  s .c om
        AppAuthenticationEntryPoint lEntryPoint = new AppAuthenticationEntryPoint();
        lEntryPoint.setRealmName("EConcept");

        pHttpSecurity.authorizeRequests().antMatchers("/rest/**").hasRole("USER").anyRequest().anonymous().and()
                .formLogin();

    } // try
    catch (Exception pException) {
        LOGGER.debug(pException.toString());
        throw new Exception(pException);
    } // catch
}

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//from   w  w  w  .  j  av  a 2s .com
    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.appverse.web.framework.backend.frontfacade.rest.authentication.basic.configuration.AppverseWebHttpBasicConfigurerAdapter.java

/**
 * CSRF is enabled by default. The authentication endopoints (login) does
 * not check CSRF (as it is the first request - you will not have a token
 * yet). After the login you will be able to retrieve the CSRF token from
 * the response header and use it in the next requests.
 *
 * Take into account that CSRF using HttpSessionCsrfRepository (default)
 * always implies to have a technical session (this does not mean you need
 * to make your services stateful. It is very well explained in Spring
 * documentation: Next paragraf if taken from:
 * http://docs.spring.io/spring-security
 * /site/docs/current/reference/htmlsingle/#csrf (Section "Loggin In": "In
 * order to protect against forging log in requests the log in form should
 * be protected against CSRF attacks too. Since the CsrfToken is stored in
 * HttpSession, this means an HttpSession will be created as soon as
 * CsrfToken token attribute is accessed. While this sounds bad in a RESTful
 * / stateless architecture the reality is that state is necessary to
 * implement practical security. Without state, we have nothing we can do if
 * a token is compromised. Practically speaking, the CSRF token is quite
 * small in size and should have a negligible impact on our architecture."
 *///from  w w w .  j a  va2 s .  c om
@Override
protected void configure(HttpSecurity http) throws Exception {
    if (securityEnableCsrf) {
        http.csrf().requireCsrfProtectionMatcher(new CsrfSecurityRequestMatcher());
    } else
        http.csrf().disable();

    http.authorizeRequests().antMatchers(baseApiPath + basicAuthenticationEndpointPath).permitAll()
            .antMatchers(baseApiPath + simpleAuthenticationEndpointPath).permitAll()
            .antMatchers(baseApiPath + "/**").fullyAuthenticated().antMatchers("/").permitAll().and().logout()
            .logoutUrl(basicAuthenticationLogoutEndpointPath)
            .logoutSuccessHandler(new SimpleNoRedirectLogoutSucessHandler()).permitAll().and().httpBasic().and()
            .sessionManagement().sessionFixation().newSession();
}

From source file:com.kazuki43zoo.jpetstore.config.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin().loginPage("/login").defaultSuccessUrl("/catalog").permitAll();
    http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/catalog")
            .deleteCookies("JSESSIONID").permitAll();
    http.authorizeRequests().mvcMatchers("/my/**").authenticated().anyRequest().permitAll();
}

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

@Override
public void configure(HttpSecurity http) throws Exception {
    if (oidcProperties.isEnabled()) {
        http.csrf().disable();//from   www  .  ja  va  2s  .  c  om
        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:com.alehuo.wepas2016projekti.configuration.DevelopmentSecurityConfiguration.java

/**
 * Konfiguroi Spring Security -lisosan/*from  w w w  .j a  v  a 2  s.  c  om*/
 * @param http
 * @throws Exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().frameOptions().sameOrigin();
    //Sallitaan psy resurssikansioihin sek H2 -konsoliin
    //        http.csrf().disable();
    //Kirjautumislokame lytyy GET -reitist /login
    http.authorizeRequests().antMatchers("/delete/**").hasAuthority(Role.ADMINISTRATOR.toString())
            .antMatchers("/js/**", "/css/**", "/manifest.json", "/resources/**", "/h2-console/**", "/register",
                    "/fi_FI.png", "/en_EN.png", "/login**", "/fonts/roboto/**")
            .permitAll().anyRequest().permitAll().anyRequest().authenticated().and().formLogin()
            .defaultSuccessUrl("/", true).loginPage("/login").permitAll().and().logout().permitAll();

}

From source file:br.com.hyperclass.snackbar.config.SecurityConfiguration.java

@Override
public void configure(final HttpSecurity http) throws Exception {
    http.addFilter(preAuthenticationFilter());
    http.addFilter(loginFilter());//  ww w  .  j ava  2s  .c o  m
    http.addFilter(anonymousFilter());
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/menu/**").hasRole("ADMIN").antMatchers("/stock/**").hasRole("ADMIN")
            .antMatchers("/order/**").permitAll().antMatchers("/cashier/**").authenticated().and().formLogin();
}