Configuring Spring Security with Spring Boot

34,053

The original question is probably best answered by just describing the options available. Some applications (services that only need basic HTTP authentication) can use the default settings in the actuator, others will need to specify security.* properties (see SecurityProperties for options) and/or an AuthenticationManager (for user account details). The next level of control comes from adding your own WebSecurityConfigurerAdapter, and you can see how to do that by looking at the "secure" sample in Spring Boot.

Share:
34,053

Related videos on Youtube

CodeChimp
Author by

CodeChimp

I have been a developer professionally since 1998, and unprefessionally for many years prior. I have a BS in Computer Science from The University of North Florida. My primary expertise is in Java/Spring, but I dabble in many different languages/frameworks/OSes.

Updated on July 05, 2022

Comments

  • CodeChimp
    CodeChimp almost 2 years

    I am new to configuring Spring Security using Java Config. I was trying to follow this posting. However, when I run my app, I get a Basic Auth challenge on all URLs, including /. Entering the either of the userid/pass combos below do not seem to work.

    My Controller:

    package com.xxx.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/")
    /**
     * Controller to handle basic "root" URLs
     * 
     * @author xxx
     * @version 0.1.0
     */
    public class RootController {
    
        /**
         * Handles '/'
         * @param model
         * @return
         */
        @RequestMapping
        public String index(Model model) {
            return "index";
        }
    
        /**
         * Handles '/signup'
         * @param model
         * @return
         */
        @RequestMapping("/signup")
        public String signup(Model model) {
            return "signup";
        }
    
        /**
         * Handles '/about'
         * @param model
         * @return
         */
        @RequestMapping("/about")
        public String about(Model model) {
            return "about";
        }
    
        /**
         * Handles '/login'
         * @param model
         * @return
         */
        @RequestMapping("/login")
        public String login(Model model) {
            return "login";
        }
    
        /**
         * Handles '/admin'
         * @param model
         * @return
         */
        @RequestMapping("/admin")
        public String admin(Model model) {
            return "admin";
        }
    }
    

    Not sure what else to try. Just looking for some guidance as to why this isn't working.

    Update

    For completeness, here is the config class:

    package com.xxx.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @Configuration
    @EnableWebSecurity
    /**
     * Configures the security for the application
     * 
     * @author XXX
     * @version 0.1.0
     *
     */
    public class WebSecurityAppConfig extends WebSecurityConfigurerAdapter {
        @Override
        /**
         * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#registerAuthentication(AuthenticationManagerBuilder)
         */
        protected void registerAuthentication(AuthenticationManagerBuilder auth)
                throws Exception {
            auth
              .inMemoryAuthentication()
                .withUser("user")  // #1
                  .password("password")
                  .roles("USER")
                  .and()
                .withUser("admin") // #2
                  .password("password")
                  .roles("ADMIN","USER");
        }
    
        @Override
        /**
         * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(WebSecurity)
         */
        public void configure(WebSecurity web) throws Exception {
            web
              .ignoring()
                 .antMatchers("/resources/**"); // #3
        }
    
        @Override
        /**
         * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(HttpSecurity)
         */
        protected void configure(HttpSecurity http) throws Exception {
            http
              .authorizeRequests()
                .antMatchers("/","/signup","/about").permitAll() // #4
                .antMatchers("/admin/**").hasRole("ADMIN") // #6
                .anyRequest().authenticated() // 7
                .and()
            .formLogin()  // #8
                .loginPage("/login") // #9
                .permitAll(); // #5
        }
    }
    

    And the WebApplicationInitializer:

    package com.xxx.config;
    
    import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
    
    /**
     * 
     * @author XXX
     * @version 0.1.0
     */
    public class SpringWebMvcInitializer extends
            AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        /**
         * 
         */
        protected Class<?>[] getRootConfigClasses() {
            return new Class[] { WebSecurityAppConfig.class };
        }
    
        @Override
        /**
         * 
         */
        protected Class<?>[] getServletConfigClasses() {
            return null;
        }
    
        @Override
        /**
         * 
         */
        protected String[] getServletMappings() {
            return null;
        }
    
    }
    

    I didn't include these before because they are pretty much a copy-paste from the referenced blog posting.

    • Dave Syer
      Dave Syer over 10 years
      I don't see Spring Boot anywhere there. Is the summary a typo?
    • CodeChimp
      CodeChimp over 10 years
      My understanding with Spring Boot is that you would put the Actuator in for Security, then add the appropriate Spring Java configuration classes in place. Am I wrong in this assumption? The only walkthrough I have found for Spring Boot with Spring Security doesn't use a Controller, and I tried to copy what it was doing as close as I could.
    • Dave Syer
      Dave Syer over 10 years
      Your understanding is correct. There are two samples (spring-boot-sample-secure, which is newish, and spring-boot-sample-actuator, which is older) that use Spring Security. The "secure" one is probably closest to your use case.
    • Dave Syer
      Dave Syer over 10 years
      (I still don't see Spring Boot anywhere in the code you posted though. I wouldn't be using AbstractAnnotationConfigDispatcherServletInitializer for instance if I were you - try SpringBootServletInitializer).
    • CodeChimp
      CodeChimp over 10 years
      Thanks for the input. Will check out the other sample when I get home. I am probably looking at an older GIT repo. Also, will switch to the SpringBootServletInitializer. Hopefully that gets me past my current road block.
  • SooCheng Koh
    SooCheng Koh over 8 years
    I followed the given 'secure' sample in Spring Boot, I'm unable to override the authenticationManager of the default security password, it still read the default security password even I have copied the ApplicationSecurity.class which have override the configure(authenticationManagerBuilder) method
  • SooCheng Koh
    SooCheng Koh over 8 years
    I found that my problem is caused by stackoverflow.com/questions/26636465/…