agusgambina
agusgambina

Reputation: 6669

Basic Authentication with Spring Boot

I am developing a small app with spring-boot and angularjs. The idea is that the backend of the application expose some services, and the frontend consume these services. I am trying to setup basic authentication

This is my pom.xml

<!-- Web Server -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- End Web Server -->

<!-- Spring Security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- End Spring Security -->

both are in the same version 1.1.1.RELEASE. My WebSecurityConfig

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**").permitAll()
                .anyRequest().authenticated();
        http
                .formLogin()
                .defaultSuccessUrl("/")
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

This is not working. Seems that the user and password are not set in memory.

When spring boot runs, it creates a default password, here is what appear in the console

AuthenticationManagerConfiguration : 

Using default security password: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

And the application work with that password.

Thank you

Upvotes: 4

Views: 32152

Answers (4)

CodeNotFound
CodeNotFound

Reputation: 1081

You can override the default user name (default value = user) and the password that is generated on the fly, by setting below properties in your application.properties file:

security.user.name=user # Default user name.
security.user.password= # Password for the default user name. A random password is logged on startup by default.

In order to register more than one user, you would need to build our own AuthenticationManager configuration.

Upvotes: 6

qanwi1970
qanwi1970

Reputation: 103

I was having this problem too, with an OAuth2 application. In the Authorization Server Config, I was using what turned out to be the global AuthenticationManager.

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints
            .tokenStore(tokenStore())
            .authenticationManager(authenticationManager)
            .accessTokenConverter(accessTokenConverter());
    }
}

But the AuthenticationManager I built is only scoped to the WebSecurityConfigurerAdapter. Instead of Overriding the configure method, I used this configureGlobal method and then everything fell into place, with no warnings or NullReferenceExceptions

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

Upvotes: 3

agusgambina
agusgambina

Reputation: 6669

This way worked, first I changed dependencies in the pom.xml

<!-- Web Server -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- End Web Server -->

<!-- Spring Security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- End Spring Security -->

Then I changed the class WebSecurityConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

@Configuration
public class WebSecurityConfig {

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return new AuthenticationManagerBuilder(new NopPostProcessor())
                       .inMemoryAuthentication().withUser("user").password("password").roles("USER")
                       .and().and().build();
    }

    private static class NopPostProcessor implements ObjectPostProcessor {
        @Override
        @SuppressWarnings("unchecked")
        public Object postProcess(Object object) {
            return object;
        }
    };
}

Upvotes: 1

Patrick Grimard
Patrick Grimard

Reputation: 7126

In your configur(HttpSecurity http) method, your last setup says .anyRequest().authenticated(), so it will require that users be authenticated for all requests.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/").permitAll()
            .anyRequest().authenticated();
}

Try the following.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().hasRole("USER")
            .and()
        .formLogin()
            .permitAll()
            .and()
        .logout()
            .permitAll()
            .and()
        .anonymous()
            .disable();
}

Upvotes: 2

Related Questions