HTTP Basic Authentication using Spring Boot’s Java based configuration

Tags: , , , ,



I am trying to set up a simple Spring Boot application secured with HTTP Basic Authentication using a single user with a hard-coded password.

So far, I got it working using XML based configuration.

How can I achieve the same result using Java based configuration?

  • SecurityConfig.java

    @EnableWebSecurity
    @ImportResource("classpath:spring-security.xml")
    public class SecurityConfig {}
    
  • spring-security.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/security"
                 xmlns:beans="http://www.springframework.org/schema/beans"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                                     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
        <http>
            <intercept-url pattern="/MyService/**" access="isAuthenticated()" />
            <http-basic />
        </http>
    
        <user-service>
            <user name="foo" password="{noop}bar" authorities="ROLE_USER" />
        </user-service>
    </beans:beans>
    

Note: I had to use @EnableWebSecurity instead of @Configuration to work around Spring Boot Issue #10236.

I am using Spring Boot 2.3.4 with Spring Security 5.3.4.

Answer

Well, if i understand correctly, you just want to setup a http connection ? Here is a code sample i wrote, and adapted to fit your xml (i think)

@Configuration("SecurityConfig") 
@Order(1) // If you have many security configs, you need to specify an order
public class SecurityFrConfiguration extends WebSecurityConfigurerAdapter {


      WARNING: You should use a password encoder, i recommend Bcrypt with 10 rounds,  salt and pepper
    @Bean
    public static PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

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


        http.sessionManagement().sessionFixation().none().and() //sessionFixation() is used for sticky sessions, if you need them
                .antMatcher("/yourWebsite/**")
                .authorizeRequests() //Here I authorize all request on the site
                .regexMatchers("/MyService/**") //Except on /Myservice where you need to be admin
                .hasAuthority("ROLE_ADMIN") //ROLE_ADMIN is an example, you could define any number of role, and making it match to any URL through regexMatchers
                .and()
                .formLogin().loginPage(YOUR_LOGIN_FORM_HERE) //This allows you to override the default form login, and use your own
                .permitAll();

    }




}

Then if you intend to really use this, you need to get the user, probably from the database, so you’ll also need something like this:

@Service
public class YourUserDetailsService implements UserDetailsService { //UserDetailsService is the interface we need to let Spring do its magic

    private final LoginsService LoginsService;

    public LibraryUserDetailsService(LoginsService loginsService) {
        this.loginsService = loginsService;
    }

    @Override
    public UserDetails loadUserByUsername(String password, String userName) throws UsernameNotFoundException {

 //Here you fetch, decrypt, and check that the password and username are correct
 //WARNING: This is a really simple example, do not use this in your applications code 
     
  Optional<GrantedAcces> access = 
  libraryLoginsService.findUser(userName,password);

  //I create a new user with the authorized role, this is store in the session
           return new User(access.get().getUserName,access.get().getPassword(), Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN")));

   }

I hope this one helps you out, and that I understood your question



Source: stackoverflow