So far we’ve built a basic spring boot application, enabled spring security and built a basic login form. In the last lesson, we expanded on the first lesson by adding different user roles and the ability to show and hide front-end content based on these roles (User Roles and Thymeleaf Extras).
Today, we’ll be looking at redirecting users with different roles to different pages after they log in.
Source code for this example can be found on github:
Following on from our previous example, we have now created a new HTML file called Admin.html. This is the page we will redirect admins to when they log in.
Now, to serve the new admin.html page, we must add this page to our MvcConfig.
As with the previous examples, this is done by creating a class, extending WebMvcConfigurerAdapter and overriding the addViewControllers method. This time adding all the earlier pages of our app and the new admin page:
In order to decide what to do when different user roles login. We have created a new field of type AuthenticationSuccessHandler. We’re setting this new configuration bean via constructor injection.
This method is in charge of overriding and configuring HttpSecurity explicitly. From the last example, we have added two lines.
First, we’ve added a new antMatcher under the authorizeRequests section, and we’ve told spring security only to allow a user with the ‘ADMIN’ role access to all endpoints starting with ‘/admin’:
Secondly, we’ve added our CustomAuthenticationSuccessHandler under the formLogin section to tell spring security to ask this CustomAuthenticationSuccessHandler what to do when a successful login occurs:
The configureGlobal method is our in-memory registry of users. We’ve added two users. One with the primary ‘USER’ role and the other with the ‘ADMIN’ role.
As you can see from our sample code below this class implements springs AuthenticationSuccessHandler class and overrides the onAuthenticationSuccess method.
Once a user is successfully logged in, this method is called and within this method, the user’s role is checked. If the user’s role is admin we redirect to the ‘/admin’ HTTP endpoint otherwise we redirect them to the ‘/index’ endpoint.
At this point, our MvcConfig takes over and serves the correct HTML page based on the viewController we created previously.
To run the demo, open the Application class and right-click run. To start the example, port 8080 will need to be available on your machine. If it is not, you can change this default in the application.properties file using:
Set this to whatever value you wish.
As always we have amended an added some additonal tests to conver a new functionality
Next up, we will be covering spring security’s Cross Site Request Forgery (CSRF) protection.