Eugene_Z
Eugene_Z

Reputation: 273

Configuration of WebSecurityConfigurerAdapter for log in

I'm trying to configure spring secutiry in my SpringBoot 2 application.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("u")
                        .password("p")
                        .roles("USER")
                        .build();

        return new InMemoryUserDetailsManager(user);
    }
}


@Configuration
public class MvcConfig implements WebMvcConfigurer {
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }
}

login.mustache

<form method="post" action="/login">
        <input type="text"     name="username" id="username" placeholder="Login" /><br>
        <input type="password" name="password" id="password" placeholder="Password" /><br>
        <input type="hidden" name="_csrf" value="{{_csrf.token}}">
        <button type="submit">Login</button>
</form>

I expect to be redirected to /users page. But actually I get error code = 302 and I appear at /login/error

SOLUTION: I've added @Bean annotation to userDetailsService() and it helped.

Upvotes: 2

Views: 1146

Answers (1)

dur
dur

Reputation: 16992

You have to expose your UserDetailsService as a bean, see Spring Boot Reference:

84.2 Change the AuthenticationManager and Add User Accounts

If you provide a @Bean of type AuthenticationManager, AuthenticationProvider, or UserDetailsService, the default @Bean for InMemoryUserDetailsManager is not created, so you have the full feature set of Spring Security available (such as various authentication options).

The easiest way to add user accounts is to provide your own UserDetailsService bean.

Your modified code:

@Bean
@Override
public UserDetailsService userDetailsService() {
    UserDetails user =
            User.withDefaultPasswordEncoder()
                    .username("u")
                    .password("p")
                    .roles("USER")
                    .build();

    return new InMemoryUserDetailsManager(user);
}

Upvotes: 2

Related Questions