Sunday, 9 April 2017

Example of multiple login pages with Spring Security and Spring Boot

I just finished preparing a Spring Security configuration for a Zuul proxy in my company when a new requirement in this area came in from the business. We needed to have different login pages for different URLs being accessed within the same application. I'm not a front-end guy, so my first thought was to enhance my existing security config. I found this topic interesting enough to investigate broader possibilities of defining separate security constraints for different URL path patterns. In this article I will describe an example on how to achieve this and how to test your configuration using Spring Boot and Thymeleaf as a templating engine. A complete project you will find here. I will mainly focus on form-based login, but at the end you will also see how to benefit from these examples in order to provide various http security types within a single application. Enjoy!


Imagine we have two home pages, that should be accessible under following paths: /regular/home and /special/home. We would like to have them secured with corresponding login forms: /regular/login, and /special/login. By deafault, Thymeleaf templates are supposed to be located in /templates directory:
├───src
│   ├───main
│   │   ├───java
│   │   │   └───com
│   │   │       └───bslota
│   │   │           │   MultiLoginApplication.java
│   │   │           │
│   │   │           └───config
│   │   │                   MvcConfig.java
│   │   │                   SecurityConfig.java
│   │   │
│   │   └───resources
│   │       │   application.yml
│   │       │
│   │       ├───static
│   │       │   └───css
│   │       │           styles.css
│   │       │
│   │       └───templates
│   │           ├───regular
│   │           │       home.html
│   │           │       login.html
│   │           │
│   │           └───special
│   │                   home.html
│   │                   login.html
│   │
│   └───test
│       └───java
│           └───com
│               └───bslota
│                       WebSecurityTest.java
│
│   .gitignore
│   mvnw
│   mvnw.cmd
│   pom.xml
Now, apart from html templates we need to configure our application, so that it resolves all views properly. To keep it simple, this should be enough for our example:
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("regular/home");
        registry.addViewController("/regular/home").setViewName("regular/home");
        registry.addViewController("/special/home").setViewName("special/home");
        registry.addViewController("/regular/login").setViewName("regular/login");
        registry.addViewController("/special/login").setViewName("special/login");
    }
}
In order to introduce security into the application, we need to declare a following dependency:

  org.springframework.boot
  spring-boot-starter-security

Hey, hold on, we are not going to do anything without testing (I hope you already have a habit of writing tests, don't you?). In order to test our security configuration, we need this library:

  org.springframework.boot
  spring-boot-starter-test
  test

Right now, what we have out of the box due to having spring-boot-starter-security dependency on classpath are:
  • HTTP-Basic security setup for all endpoints,
  • randomly generated password logged in console during startup for a user named user.
As we mentioned at the beginning, we want to have a form-based login. Let's define our requirements in a couple of simple tests, then:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class WebSecurityTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testIfRegularHomePageIsSecured() throws Exception {
        final ResultActions resultActions = mockMvc.perform(get("/regular/home"));
        resultActions
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("http://localhost/regular/login"));
    }

    @Test
    @WithMockUser
    public void testIfLoggedUserHasAccessToRegularHomePage() throws Exception {
        final ResultActions resultActions = mockMvc.perform(get("/regular/home"));
        resultActions
                .andExpect(status().isOk())
                .andExpect(view().name("regular/home"));
    }

    @Test
    @WithMockUser
    public void testIfLoggedUserHasAccessToSpecialHomePage() throws Exception {
        final ResultActions resultActions = mockMvc.perform(get("/special/home"));
        resultActions
                .andExpect(status().isOk())
                .andExpect(view().name("special/home"));
    }

}

What you should know from this code is that we are creating a mock servlet environment (webEnvironment = SpringBootTest.WebEnvironment.MOCK) and auto-configuring MockMvc (@AutoConfigureMockMvc) - a neat and powerful tool for web controller testing. With this setup you don't need to build and configure MockMvc on your own - you can simply inject it as a regular bean dependency. Spring Boot never stops fascinating me.
We have three tests written here. The first one says:

given:
  anonymous user
when:
  trying to access /regular/home URL
then:
  I get 302 HTTP response
and:
  I'm redirected to /regular/login page

And the second one:

given:
  a principal with username "user" and password "password"
when:
  trying to access /regular/home URL
then:
  I get 200 HTTP response
and:
  I access regular/home view

The third one is almost the same as the second (the only difference is the url that is being accessed with MockMvc). As long as when-then parts should be rather clear, the given part might be a bit confusing. In the first test we have not defined any security constraints, so the MockMvc call will be be considered as one from anonymous user. In the second test, though, we are using @WithMockUser annotation which emulates a call as if it is performed by authenticated user. The SecurityContext within so-annotated test will contain an implementation of Authentication interface of type UsernamePasswordAuthenticationToken. With this annotation, you can adjust username, roles/authorities and password as well. By default, we will have a principal with following details:
  • username: user
  • password: password
  • roles: USER 
It would be sufficient to stick to defaults here. Okay, we have some tests, but they fail. Sure they do! Here is what we need to do now:
  • Define AuthenticationManager (in-memory one will be enough for this example) and create appropriate user,
  • Configure HttpSecurity so that all resources are secured with form-based login under /regular/login.

 @Configuration
public class SecurityConfig {

    @Configuration
    public static class RegularSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //@formatter:off
            http
                .authorizeRequests()
                    .antMatchers("/css/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/regular/login")
                    .defaultSuccessUrl("/regular/home")
                    .permitAll()
                    .and()
                .logout()
                    .logoutUrl("/regular/logout")
                    .permitAll();
            //@formatter:on
        }
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("password")
                .roles("USER");
    }
}
Good, now within configureGlobal method we configured an in-memory AuthenticationManager and created a user, as desired. We also declared a RegularSecurityConfig class that extends WebSecurityConfigurerAdapter and overrides configure(HttpSecurity) method - this gives us the ability to change default pre-configured security behaviour. Within the configure(HttpSecurity) method, we:
  • decided to authenticate any request (apart from accessing css files - nevermind that part),
  • set login page URL to /regular/login,
  • set default success login URL to /regular/home - the place where users will be directed after authenticating, not having visited a secured page,
  • set logout URL to /regular/logout.
Of course we don't need logout or default success URL details being defined to complete this example but you will appreciate it when you download and run the whole app, I hope. All right, now all tests are passed. What's next? Tests again:
    @Test
    public void testIfSpecialHomePageIsSecured() throws Exception {
        final ResultActions resultActions = mockMvc.perform(get("/special/home"));
        resultActions
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("http://localhost/special/login"));
    }
This tests is very similar to the previously written one. We are checking whether anonymous user trying to access /special/home page gets redirected to /special/login. Surely this test won't pass. The remedy is to add a following code into SecurityConfig class:
    @Configuration
    @Order(1)
    public static class SpecialSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //@formatter:off
            http
                .antMatcher("/special/**")
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/special/login")
                    .defaultSuccessUrl("/special/home")
                    .permitAll()
                    .and()
                .logout()
                    .logoutUrl("/special/logout")
                    .permitAll();
            //@formatter:on
        }
    }

We just created yet another WebSecurityConfigurerAdapter extension. When you look at the body of configure method, then you will see that it is pretty similar to the one that we had defined previously. The difference is that we have an antMatcher, that enables us to filter and apply this settings only for URLs that begin with /special/ prefix. And how does Spring know which configure method (from which WebSecurityConfigurerAdapter extension) should be invoked first? It is because the @Order(1) annotation.
Yep, we got it! We have implemented and tested our Spring MVC configuration with two separate login pages for different URLs being accessed. This example should show you how many possibilitis Spring Security gives you. Do not think that this kind of configuration is limited to form-based login - you could declare HTTP-Basic security for all requests that concerns /special/** URLs as well or set any security constraints you like for whatever path templates.

9 comments:

  1. Bro I think it would be more great if you upload its source code too...

    ReplyDelete
  2. Good Post! Thank you so much for sharing the nice post, it was so good to read and useful to improve
    Java Training in Electronic City

    ReplyDelete
  3. Your article is really very creative. you post all the useful things. If you are interested to know server hosting then choose USA Dedicated Server with Onlive Server. It offers hassle-free web hosting solutions worldwide.

    ReplyDelete
  4. Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job. Keep it up qlik sense certification

    ReplyDelete