Search code examples
javaspringspring-securityjhipstermatcher

Spring Security - Authorize Request for certain URL & HTTP-Method using HttpSecurity


Is there any way to authorize a POST http-request to a specific URL using org.springframework.security.config.annotation.web.builders.HttpSecurity ?

I'm using HttpSecurity as:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
            .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
        .and()
            .rememberMe()
            .rememberMeServices(rememberMeServices)
            .key(env.getProperty("jhipster.security.rememberme.key"))
        .and()
            .formLogin()
            .loginProcessingUrl("/api/authentication")
            .successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler)
            .usernameParameter("j_username")
            .passwordParameter("j_password")
            .permitAll()
        .and()
            .logout()
            .logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler)
            .deleteCookies("JSESSIONID")
            .permitAll()
        .and()
            .headers()
            .frameOptions()
            .disable()
            .authorizeRequests()
                .antMatchers("/api/register").permitAll()
                .antMatchers("/api/activate").permitAll()
                .antMatchers("/api/authenticate").permitAll()
                .antMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/api/subscriptions").permitAll()
                .antMatchers("/api/**").authenticated();
}

I would like to allow only POST requests to the path "/api/subscription".


Solution

  • Take a look at Spring Data REST + Spring Security which has

    http
      .httpBasic().and()
      .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
        .antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")
        .antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN");