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.erudika.para.security.SecurityConfig.java

/**
 * Configures the protected private resources
 *
 * @param http HTTP sec object//from   ww w. j  a va 2s.  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.apache.atlas.web.security.AtlasSecurityConfig.java

protected void configure(HttpSecurity httpSecurity) throws Exception {

    //@formatter:off
    httpSecurity.authorizeRequests().anyRequest().authenticated().and().headers().disable().servletApi().and()
            .csrf().disable().sessionManagement().enableSessionUrlRewriting(false)
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS).sessionFixation().newSession().and()
            .formLogin().loginPage("/login.jsp").loginProcessingUrl("/j_spring_security_check")
            .successHandler(successHandler).failureHandler(failureHandler).usernameParameter("j_username")
            .passwordParameter("j_password").and().logout().logoutSuccessUrl("/login.jsp")
            .deleteCookies("ATLASSESSIONID").logoutUrl("/logout.html").and().httpBasic()
            .authenticationEntryPoint(getDelegatingAuthenticationEntryPoint());
    //@formatter:on

    if (configuration.getBoolean("atlas.server.ha.enabled", false)) {
        LOG.info("Atlas is in HA Mode, enabling ActiveServerFilter");
        httpSecurity.addFilterAfter(activeServerFilter, BasicAuthenticationFilter.class);
    }/*  w  ww.jav a  2s  . com*/
    httpSecurity.addFilterAfter(staleTransactionCleanupFilter, BasicAuthenticationFilter.class)
            .addFilterAfter(ssoAuthenticationFilter, BasicAuthenticationFilter.class)
            .addFilterAfter(atlasAuthenticationFilter, SecurityContextHolderAwareRequestFilter.class)
            .addFilterAfter(csrfPreventionFilter, AtlasAuthenticationFilter.class)
            .addFilterAfter(atlasAuthorizationFilter, FilterSecurityInterceptor.class);
}

From source file:org.flowable.rest.conf.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    HttpSecurity httpSecurity = http.authenticationProvider(authenticationProvider()).sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();

    // Swagger docs
    if (isSwaggerDocsEnabled()) {
        httpSecurity.authorizeRequests().antMatchers("/docs/**").permitAll();

    } else {/*  w w  w  .  j  a  v a2s.c  o  m*/
        httpSecurity.authorizeRequests().antMatchers("/docs/**").denyAll();

    }

    httpSecurity.authorizeRequests()
            .requestMatchers(EndpointRequest.to(InfoEndpoint.class, HealthEndpoint.class)).authenticated()
            .requestMatchers(EndpointRequest.toAnyEndpoint()).hasAnyAuthority(SecurityConstants.ACCESS_ADMIN);

    // Rest API access
    if (isVerifyRestApiPrivilege()) {
        httpSecurity.authorizeRequests().anyRequest().hasAuthority(SecurityConstants.PRIVILEGE_ACCESS_REST_API)
                .and().httpBasic();

    } else {
        httpSecurity.authorizeRequests().anyRequest().authenticated().and().httpBasic();

    }
}

From source file:org.kuali.coeus.sys.framework.security.SpringRestSecurity.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();/*from   w ww  . j a  v  a2s  .c o  m*/
    http.authorizeRequests().regexMatchers(V1_REST_SERVICES_REGEX).hasRole(ADMIN_ROLE).and().httpBasic();
}

From source file:org.opentestsystem.ap.iat.config.SecurityConfig.java

/**
 * Defines the web based security configuration.
 *
 * @param http It allows configuring web based security for specific http requests.
 * @throws Exception/*from   w  w w.  j a  v a  2s.c o m*/
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().authenticationEntryPoint(samlEntryPoint());
    http.csrf().disable();
    http.addFilterBefore(forwardedHeaderFilter(), ChannelProcessingFilter.class)
            .addFilterAfter(metadataGeneratorFilter(), ForwardedHeaderFilter.class)
            .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class);
    http.headers().frameOptions().sameOrigin();
    http.authorizeRequests()
            .antMatchers("/saml/**", "/manage/**/health**", "/manage/**/info**", "/assets/**", "**.js",
                    "favicon.**", "/fontawesome**", "/glyphicons**", "/api/sec/**", "/api/ivs/**",
                    "/error/403.html", "/keepalive")
            .permitAll();
    http.authorizeRequests().antMatchers("/**").hasAnyRole("ADMIN", "USER");
    http.logout().logoutSuccessUrl("/");

    http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}

From source file:org.schedoscope.metascope.conf.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/*", "/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   www .  j  av a 2s .  c  om*/
        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:org.springframework.cloud.dataflow.server.config.security.OAuthSecurityConfiguration.java

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

    final RequestMatcher textHtmlMatcher = new MediaTypeRequestMatcher(
            new BrowserDetectingContentNegotiationStrategy(), MediaType.TEXT_HTML);

    final BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
    basicAuthenticationEntryPoint.setRealmName(securityProperties.getBasic().getRealm());
    basicAuthenticationEntryPoint.afterPropertiesSet();

    final Filter oauthFilter = oauthFilter();
    BasicAuthenticationFilter basicAuthenticationFilter = new BasicAuthenticationFilter(providerManager(),
            basicAuthenticationEntryPoint);

    http.addFilterAfter(oauthFilter, basicAuthenticationFilter.getClass());
    http.addFilterBefore(basicAuthenticationFilter, oauthFilter.getClass());
    http.addFilterBefore(oAuth2AuthenticationProcessingFilter(), basicAuthenticationFilter.getClass());

    http.authorizeRequests()
            .antMatchers("/security/info**", "/login**", dashboard("/logout-success-oauth.html"),
                    dashboard("/styles/**"), dashboard("/images/**"), dashboard("/fonts/**"),
                    dashboard("/lib/**"))
            .permitAll().anyRequest().authenticated().and().httpBasic().and().logout()
            .logoutSuccessUrl(dashboard("/logout-success-oauth.html")).and().csrf().disable()
            .exceptionHandling()/*from w w  w  . j a  v a  2 s . c o  m*/
            .defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login"), textHtmlMatcher)
            .defaultAuthenticationEntryPointFor(basicAuthenticationEntryPoint, AnyRequestMatcher.INSTANCE);

    securityStateBean.setAuthenticationEnabled(true);
    securityStateBean.setAuthorizationEnabled(false);
}

From source file:org.springframework.security.config.annotation.web.configuration.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>/* www.ja  va  2s  .  co m*/
 * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
 * </pre>
 *
 * @param http the {@link HttpSecurity} to modify
 * @throws Exception if an error occurs
 */
// @formatter:off
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();
}