Adding Spring Security to an existing Spring web application (using JavaConfig)

I have a Spring MVC Rest Web web application for which I am in the process of adding Spring's security layer.

While I am looking through Spring documentation , I cannot understand the meaning of section 3.1.3. I copy / paste the contents of the section below.

If we were using Spring elsewhere in our application we probably already had a WebApplicationInitializer that is loading our Spring Configuration. If we use the previous configuration we would get an error. Instead, we should register Spring Security with the existing ApplicationContext. For example, if we were using Spring MVC our SecurityWebApplicationInitializer would look something like the following:

import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
      extends AbstractSecurityWebApplicationInitializer {

}

This would simply only register the springSecurityFilterChain Filter for every URL in your application. After that we would ensure that SecurityConfig was loaded in our existing ApplicationInitializer. For example, if we were using Spring MVC it would be added in the getRootConfigClasses()

public class MvcWebApplicationInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class };
    }

    // ... other overrides ...
}

So I already have

an Initializer.java (replacement of web.xml)
Config.java - Root Context
RestServlet.java - Servlet Context

Here is my Initializer.java

public class Initializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {

      // Create the 'root' Spring application context
      AnnotationConfigWebApplicationContext rootContext =
        new AnnotationConfigWebApplicationContext();
      rootContext.register(Config.class);

      // Manage the lifecycle of the root application context
      container.addListener(new ContextLoaderListener(rootContext));
//      container.addListener(new ContextLoaderListener(rootContext));

      // Create the dispatcher servlet Spring application context
      AnnotationConfigWebApplicationContext dispatcherContext =
        new AnnotationConfigWebApplicationContext();
      dispatcherContext.register(RestServlet.class);

      // Register and map the dispatcher servlet
      ServletRegistration.Dynamic dispatcher =
        container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/");


    }
 }

To add Spring's security level, I added the following

SecurityConfig.java
SecurityInitializer.java

SecurityConfig.java (This must be verified using the data in memory).

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

       @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

SecurityInitializer.java

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer
              {


    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class };
    }

, , . ( 3.2.3 ), AbstractSecurityWebApplicationInitializer AbstractAnnotationConfigDispatcherServletInitializer.

, REST. , jsps ( !). - OAuth2, frontend webapp ( Angular) REST api . Facebook Google+. Spring , . , - , , .

+3
3

@Configuration :

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    FooUserDetailsService fooUserDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.fooUserDetailsService).passwordEncoder(passwordEncoder);
    }

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

        http
            .authorizeRequests()
                .antMatchers("/signup").anonymous()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .antMatchers("/api/**").hasRole("USER")
                .antMatchers("/**").hasAnyRole("USER", "ADMIN")
            .and()
                .csrf().disable()
                .formLogin()
                .loginProcessingUrl("/j_spring_security_check")
                .loginPage("/auth").failureUrl("/auth")
                .usernameParameter("j_username").passwordParameter("j_password")
                .defaultSuccessUrl("/")
            .and()
                .logout()
                .logoutUrl("/j_spring_security_logout")
                .logoutSuccessUrl("/auth");
    }
}

- , , , , , , , API REST, .

, :

public class WebApplicationInitialiser implements WebApplicationInitializer {

    private static Class<?>[]  configurationClasses = new Class<?>[] {
        WebSecurityConfiguration.class
    };
}

( , ) createContext(configurationClasses);

, .

+4

, , - "3.4. ". , RESTful. , JSP, JSON XML. - RESTful, Spring.io(http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch18s02.html), spring 3.0, , spring 4.0, , REST. REST, @RequestMapping("/users/{userid}", method=RequestMethod.GET).

3.4, .. .antMatchers("/users/**").hasRole("USER")

, , 2. , . "3.5.1. " . .

+1

-, , . - , DispatcherServlet java-config, AbstractAnnotationConfigDispatcherServletInitializer โ†’ root-config ContextLoaderListener; , , AbstractSecurityWebApplicationInitializer, ContextLoaderListener . , : ContextLoaderListener -config-config beans, --config beans AbstractSecurityWebApplicationInitializer.

0

All Articles