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.chortitzer.web.WebSecurityConfig.java

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

    // Have to disable it for POST methods:
    // http://stackoverflow.com/a/20608149/1199132
    http.csrf().disable();//  w w w .  j a  va 2 s .c  o m

    // Logout and redirection:
    // http://stackoverflow.com/a/24987207/1199132
    http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).invalidateHttpSession(true)
            .logoutSuccessUrl("/login.xhtml");

    http.authorizeRequests()
            // Some filters enabling url regex:
            // http://stackoverflow.com/a/8911284/1199132
            .regexMatchers("\\A/page1.xhtml\\?param1=true\\Z", "\\A/page2.xhtml.*").permitAll()
            //Permit access for all to error and denied views
            .antMatchers("/500.xhtml", "/denied.xhtml").permitAll()
            // Only access with admin role
            .antMatchers("/admin/**").hasRole("ADMIN")
            //Permit access only for some roles
            .antMatchers("/usi/**").hasAnyRole("ADMIN", "energia")
            //If user doesn't have permission, forward him to login page
            .and().formLogin().loginPage("/login.xhtml").loginProcessingUrl("/login")
            .defaultSuccessUrl("/index.xhtml").and().exceptionHandling().accessDeniedPage("/denied.xhtml");
}

From source file:net.orpiske.tcs.service.config.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    /**/*from w  w  w  .  j a  v a 2  s  .  co m*/
     * Disabling CSRF because ... well ... because ... f**** you. I know it's good
     * but I need to research more about it. For now, I just want to get this site
     * up an running.
     *
     * Ref.:
     * http://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/
     */
    http.csrf().disable();

    http.authorizeRequests().antMatchers(HttpMethod.POST, "/domain/**").hasRole("USER").and().httpBasic();

    http.authorizeRequests().antMatchers(HttpMethod.GET, "/domain/**").permitAll();

    http.authorizeRequests().antMatchers(HttpMethod.POST, "/references/**").hasRole("USER").and().httpBasic();

    http.authorizeRequests().antMatchers("/tagcloud/**", "/tagcloud/domain/**").permitAll();
}

From source file:eu.openanalytics.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http/*from   w  w  w  . j  av  a2  s . c o m*/
            // must disable or handle in proxy
            .csrf().disable()
            // disable X-Frame-Options
            .headers().frameOptions().sameOrigin();

    if (hasAuth(environment)) {
        // Limit access to the app pages
        http.authorizeRequests().antMatchers("/login").permitAll();
        for (ShinyApp app : appService.getApps()) {
            String[] appRoles = appService.getAppRoles(app.getName());
            if (appRoles != null && appRoles.length > 0)
                http.authorizeRequests().antMatchers("/app/" + app.getName()).hasAnyRole(appRoles);
        }

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

        // All other pages are available to authenticated users
        http.authorizeRequests().anyRequest().fullyAuthenticated();

        http.formLogin().loginPage("/login").and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessHandler(logoutHandler)
                .logoutSuccessUrl("/login");
    }
}

From source file:com.hillert.botanic.config.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter(
            sessionRepository);//from w w w  .  jav a  2 s . c o  m
    sessionRepositoryFilter.setHttpSessionStrategy(new HeaderHttpSessionStrategy());
    http.addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class).csrf().disable();

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

    http.authorizeRequests().antMatchers(HttpMethod.POST, "/api/plants/**")
            .hasRole(DefaultUserDetailsService.ROLE_ADMIN);

}

From source file:org.italiangrid.storm.webdav.spring.web.SecurityConfig.java

protected void addAccessRules(HttpSecurity http) throws Exception {

    for (StorageAreaInfo sa : saConfiguration.getStorageAreaInfo()) {

        for (String ap : sa.accessPoints()) {

            String writeAccessRule = String.format("hasRole('%s') and hasRole('%s')",
                    SAPermission.canRead(sa.name()).getAuthority(),
                    SAPermission.canWrite(sa.name()).getAuthority());

            http.authorizeRequests().requestMatchers(new ReadonlyHTTPMethodMatcher(ap + "/**"))
                    .hasAuthority(SAPermission.canRead(sa.name()).getAuthority());

            http.authorizeRequests().antMatchers(ap + "/**").access(writeAccessRule);
        }/*from w ww . j a  v  a2  s  . c  o  m*/
    }
}

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

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();/*from w  w  w.j  ava2  s  .  co m*/

    http.addFilterAfter(samlFilter(), BasicAuthenticationFilter.class).exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint);

    http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/error").permitAll()
            .antMatchers("/saml/**").permitAll().antMatchers("/redirect").permitAll()
            .antMatchers("/api/public/v1/**").permitAll().antMatchers("/api/admin/**")
            .access(Constants.ADMIN_ROLE_REQUIRED).antMatchers("/metrics/metrics/*")
            .access(securityUtils.getWhitelistedIpAccess()).anyRequest().authenticated();
}

From source file:com.naveen.demo.config.Saml2SSOConfig.java

/**
  * Defines the web based security configuration.
  * //from  w w  w  .ja  v a2 s  .  c  o  m
  * @param   http It allows configuring web based security for specific http requests.
  * @throws  Exception 
  */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/js/**", "/libs/**", "/login**").permitAll();

    http.httpBasic().authenticationEntryPoint(samlEntryPoint());
    http.csrf().disable();
    http.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class).addFilterAfter(samlFilter(),
            BasicAuthenticationFilter.class);

    http.antMatcher("/login/**").authorizeRequests().anyRequest().authenticated();

    /* http        
    .authorizeRequests()
    .antMatchers("/").permitAll()
    .antMatchers("/error").permitAll()
    .antMatchers("/saml/**").permitAll()
    .anyRequest().authenticated();*/

    http.logout().logoutSuccessUrl("/");
}

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 ww 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:jp.pigumer.sso.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().authenticationEntryPoint(samlEntryPoint());
    http.csrf().disable();//from   www. j  a  v  a 2 s.c o m
    http.authorizeRequests().antMatchers("/", "/saml/**").permitAll().anyRequest().authenticated();
    http.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class).addFilterAfter(samlFilter(),
            BasicAuthenticationFilter.class);
    http.logout().logoutSuccessUrl("/");

}

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  w  w.  j  a v a 2  s  .c om

    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());

}