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:org.openlmis.fulfillment.security.ResourceServerSecurityConfiguration.java

@Override
public void configure(HttpSecurity http) throws Exception {
    http.addFilterAfter(new OncePerRequestFilter() {
        @Override/* w ww  .ja  va 2 s . c  om*/
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            // We don't want to allow access to a resource with no token so clear
            // the security context in case it is actually an OAuth2Authentication
            if (tokenExtractor.extract(request) == null) {
                SecurityContextHolder.clearContext();
            }
            filterChain.doFilter(request, response);
        }
    }, AbstractPreAuthenticatedProcessingFilter.class);
    http.csrf().disable();

    http.authorizeRequests()
            .antMatchers("/fulfillment", "/webjars/**", "/fulfillment/webjars/**", "/fulfillment/docs/**")
            .permitAll().antMatchers("/**").fullyAuthenticated();
}

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

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

    final List<GrantedAuthority> anonymousAccessPermissions = new ArrayList<GrantedAuthority>();

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

        if (sa.anonymousReadEnabled()) {

            anonymousAccessPermissions.add(SAPermission.canRead(sa.name()));
        }/*  w  w w  .  j  ava2 s .  com*/
    }

    VOMSAuthenticationProvider prov = new VOMSAuthenticationProvider();

    http.csrf().disable();

    http.authenticationProvider(prov).addFilter(buildVOMSAuthenticationFilter(prov));

    if (!anonymousAccessPermissions.isEmpty()) {
        http.anonymous().authorities(anonymousAccessPermissions);
    }

    if (serviceConfiguration.isAuthorizationDisabled()) {

        http.authorizeRequests().anyRequest().permitAll();

    } else {

        http.authorizeRequests().accessDecisionManager(accessDecisionManager());
        addAccessRules(http);

    }
}

From source file:cn.org.once.cstack.config.SecurityConfiguration.java

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

    // Login Form
    http.formLogin().loginProcessingUrl("/user/authentication").successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler).usernameParameter("j_username")
            .passwordParameter("j_password").permitAll();

    // Logout/*  www.jav a2 s . co m*/
    http.logout().logoutUrl("/user/logout").logoutSuccessHandler(ajaxLogoutSuccessHandler)
            .deleteCookies("JSESSIONID", "XSRF-TOKEN", "isLogged").invalidateHttpSession(true).permitAll();

    // CSRF protection
    // enable for any profils
    activateProtectionCRSF(http);
    // enable for any profils
    disableProtectionCRSF(http);

    // Routes security
    http.authorizeRequests().antMatchers("/gitlab/**").permitAll().antMatchers("/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").and().exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint);
    if ("true".equals(System.getProperty("httpsOnly"))) {
        logger.info("launching the application in HTTPS-only mode");
        http.requiresChannel().anyRequest().requiresSecure();
    }
}

From source file:it.infn.mw.iam.config.saml.SamlConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    String pattern = "/saml/**";

    http.antMatcher(pattern);//w  w w . jav  a2 s  . co m

    http.csrf().ignoringAntMatchers(pattern);

    http.authorizeRequests().antMatchers(pattern).permitAll();

    http.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class).addFilterAfter(samlFilter(),
            BasicAuthenticationFilter.class);
}

From source file:fr.treeptik.cloudunit.config.SecurityConfiguration.java

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

    // Login Form
    http.formLogin().loginProcessingUrl("/user/authentication").successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler).usernameParameter("j_username")
            .passwordParameter("j_password").permitAll();

    // Logout// w  w  w .j a va 2 s  .  co  m
    http.logout().logoutUrl("/user/logout").logoutSuccessHandler(ajaxLogoutSuccessHandler)
            .deleteCookies("JSESSIONID", "XSRF-TOKEN", "isLogged").invalidateHttpSession(true).permitAll();

    // CSRF protection
    // enable for any profils
    activateProtectionCRSF(http);
    // enable for any profils
    disableProtectionCRSF(http);

    // Routes security
    http.authorizeRequests().antMatchers("/application/**").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
            .antMatchers("/server/**").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/module/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/file/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/image/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/user/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/logs/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/snapshot/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/monitoring/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/messages/**")
            .hasAnyAuthority("ROLE_USER", "ROLE_ADMIN").antMatchers("/admin/**").hasAnyAuthority("ROLE_ADMIN")
            .antMatchers("/user/check", "/nopublic/**").permitAll().and().exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint);

    if ("true".equals(System.getProperty("httpsOnly"))) {
        logger.info("launching the application in HTTPS-only mode");
        http.requiresChannel().anyRequest().requiresSecure();
    }
}

From source file:org.appverse.web.framework.backend.security.oauth2.resourceserver.configuration.jwtstore.ResourceServerWithJWTStoreConfigurerAdapter.java

@Override
public void configure(HttpSecurity http) throws Exception {
    // In this OAuth2 scenario with implicit flow we both login the user and obtain the token
    // in the same endpoint (/oauth/authorize). User credentials will be passed as "username" and 
    // "password" form. 
    // This might be different in other scenarios, for instance if we wanted to implement
    // authorization code flow to support token refresh.
    http.httpBasic().disable()//from w  w w .  j  av  a  2 s .com
            // Test filter gives problems because is redirecting to / is not saving the request to redirect properly
            .logout().logoutUrl(apiPath + oauth2LogoutEndpointPath).logoutSuccessHandler(oauth2LogoutHandler());

    if (swagerEnabled) {
        if (!swaggerCloudMode) {
            // If swagger is enabled and we are not in 'cloud mode' (behind a Zuul OAuth2 enabled proxy)
            // we need to permit certain URLs and resources for Swagger UI to work with OAuth2
            http.authorizeRequests().antMatchers(swaggerOauth2AllowedUrlsAntMatchers.split(",")).permitAll();
        }
    } else {
        http.authorizeRequests().antMatchers(swaggerOauth2AllowedUrlsAntMatchers.split(",")).denyAll();
    }
    http.authorizeRequests().anyRequest().authenticated();
}

From source file:com.xiovr.unibot.config.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    //      http.authorizeRequests().antMatchers("/css/**", "/images/**, /js/**")
    //            .permitAll().anyRequest().authenticated();
    ///*  w  w  w  . j av  a2 s  .c  o m*/
    //      http.formLogin().failureUrl("/login").loginPage("/login")
    //            .loginProcessingUrl("/login/submit")
    //            .usernameParameter("username").passwordParameter("password")
    //            .defaultSuccessUrl("/", false).permitAll();
    //      http.logout().logoutUrl("/logout").invalidateHttpSession(true)
    //            .permitAll();

    http.headers().addHeaderWriter(
            new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN));
    http.headers().xssProtection();
    http.headers().cacheControl();
    http.headers().contentTypeOptions();
    HstsHeaderWriter writer = new HstsHeaderWriter(false);
    writer.setRequestMatcher(AnyRequestMatcher.INSTANCE);
    http.headers().addHeaderWriter(writer);
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/css/**", "/images/**").permitAll().anyRequest().authenticated();
    http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/login")
            .loginProcessingUrl("/login/submit").defaultSuccessUrl("/", false).permitAll().and()
            .exceptionHandling().accessDeniedPage("/error").and().logout().permitAll();
}

From source file:com.appspot.potlachkk.config.WebSecurityConfig.java

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

    // We don't want to cache requests during login
    http.requestCache().requestCache(new NullRequestCache());

    //I am not sure if this configuration is not a "work-aroud"
    //maybe there is a simpler/more elegant solution

    //Avoid CSRF token related problems with mobile clients
    http.csrf().disable();/*from  w  ww  .  j  a  v a2s  .com*/

    //if attempt to access protected URL without authentication
    //send the client HTTP code (instead of redirecting to login form)
    //now to login a POST to /login with password=pass1&username=user1 
    //Content-Type: application/x-www-form-urlencoded must be sent
    http.exceptionHandling().authenticationEntryPoint(JSON_AUTHENTICATION_ENTRY_POINT);

    http.formLogin().successHandler(NO_REDIRECT_SUCCESS_HANDLER).failureHandler(NO_REDIRECT_FAILURE_HANDLER)
            .permitAll().and().logout().logoutUrl("/logout").logoutSuccessHandler(JSON_LOGOUT_SUCCESS_HANDLER)
            .deleteCookies("JSESSIONID").invalidateHttpSession(true).permitAll();

    //GAE - specific localhost maintenance URL
    http.authorizeRequests().antMatchers("/_ah/**").permitAll();

    //configuration URL - should be disabled in production
    http.authorizeRequests().antMatchers("/config").permitAll();
    http.authorizeRequests().antMatchers("/delconfig").permitAll();

    //test
    http.authorizeRequests().antMatchers("/image/**").permitAll();
    //http.authorizeRequests().antMatchers("/chain/**").permitAll();
    //http.authorizeRequests().antMatchers("/gift/**").permitAll();

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

From source file:scratch.cucumber.example.SecurityConfiguration.java

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

    // The http.formLogin().defaultSuccessUrl("/path/") method is required when using stateless Spring Security
    // because the session cannot be used to redirect to the page that was requested while signed out. Unfortunately
    // using this configuration method will cause our custom success handler (below) to be overridden with the
    // default success handler. So to replicate the defaultSuccessUrl("/path/") configuration we will instead
    // correctly configure and delegate to the default success handler.
    final SimpleUrlAuthenticationSuccessHandler delegate = new SimpleUrlAuthenticationSuccessHandler();
    delegate.setDefaultTargetUrl("/spring/");

    // Make Spring Security stateless. This means no session will be created by Spring Security, nor will it use any
    // previously existing session.
    http.sessionManagement().sessionCreationPolicy(STATELESS);
    // Disable the CSRF prevention because it requires the session, which of course is not available in a
    // stateless application. It also greatly complicates the requirements for the sign in POST request.
    http.csrf().disable();//from   w  w  w  . j  a  v  a  2 s. c  o m
    // Viewing any page requires authentication.
    http.authorizeRequests().anyRequest().authenticated();
    http.formLogin()
            // Viewing the sign in page does not require authentication.
            .loginPage("/spring/signIn").permitAll()
            // Override the sign in success handler with our stateless implementation. This will update the response
            // with any headers and cookies that are required for subsequent authenticated requests.
            .successHandler(new StatelessAuthenticationSuccessHandler(authenticationBinder, delegate));
    http.logout().logoutUrl("/spring/signOut").logoutSuccessUrl("/spring/");
    // Add our stateless authentication filter before the default sign in filter. The default sign in filter is
    // still used for the initial sign in, but if a user is authenticated we need to acknowledge this before it is
    // reached.
    http.addFilterBefore(new StatelessAuthenticationFilter(authenticationBinder, securityContextHolder),
            UsernamePasswordAuthenticationFilter.class);
}