javasessionspring-bootspring-mongo

Understanding authentication and session management using Spring boot


I have made a spring boot project with mongo db as backend. I want to ensure that users are authenticated and authorized while maintaining some kind of in memory session (using redis or something in built in spring session)
I have been through lot of turorials like this, this, this etc

All of them ask you to extend WebSecurityConfigAdapter, configure HttpSecurity and provide a UserDetailService. Which I have done the following way.

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService(){
        return new StockUserDetailService();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/logout/**").permitAll()
                .antMatchers("/admin/**").hasAuthority("ADMIN")
                .antMatchers("/broker/**").hasAnyAuthority("BROKER")
                .anyRequest().fullyAuthenticated();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }
}

But what I don't understand is where is the sessin management taking place and what is the url that the user should use to login? If I write a controller with mapping for /login, what should my action be inside the login controller. I really am not getting the whole picture.



UPDATE

I tried posting to /login. I get this error

{
"timestamp": 1494842451672,
"status": 403,
"error": "Forbidden",
"message": "Could not verify the provided CSRF token because your session was not found.",
"path": "/login"
}

Solution

  • Spring manages the /login route for you. You just have to send the POST request to it with the user credentials. If you want to specify another login URL you can do with .loginProcessingUrl("/myCustomLoginUrl") For UserDetailsService you have to provide your own implementation which implements the loadUserByUsername(String userName) method which retrieves the user from databse or any persistence storage you are using and returns a org.springframework.security.core.userdetails.User with corresponding authorities. Please see the following official docs: https://spring.io/guides/gs/securing-web/