Last updated: 2024-06-24

  1. Learn
  2. Spring Security
  3. Multiple Configs

Multiple configurations with Spring Security

Spring Security offers all necessary means to implement even complex scenarios in our application. What is the required setup in order to use multiple configurations in parallel app?

The previous articles have already explained how to protect a REST API with JWT and a Thymeleaf frontend with the form-based login. Let's look at all the next steps to combine these two approaches.

The correct use of the securityMatcher(...) method together with the @Order(...) annotation in our security configuration is key to a working setup. A request can only ever be processed by one configuration - "double" authentication is not possible in Spring Security and makes no sense. Therefore, the more specific securityMatcher(...) is given a lower order so that the request is checked first. Our configuration for JWT now looks like this.

Adapted configuration for JWT

All requests below /api/... are now checked by this configuration - this means that a valid token must be available for these paths. All other requests are ignored and picked up by our configuration for the form-based login with the higher order.

Adapted configuration for form-based login

The @Order(...) annotation must be placed at the method so that the sorting is defined at runtime. A further restriction by the securityMatcher(...) method is not necessary for the form config - it will only apply if the first config hasn't matched. If our configurations load the users from the same table, we only need to provide one UserDetailsService in total.

Access to the "/authenticate" endpoint is explicitly allowed so that a token can be determined for the API. In addition, "/error" must be accessible without further restrictions. This endpoint is called by Spring Boot via a forward if the authentication for a /api/... request fails. Without enabling this path, a client would be redirected to the login form - but we want to see the error output instead.

With these changes we have already set up our application for the use of multiple security configurations!

Bring back the joy to Spring Security - add multiple Spring Security configurations to your application in Bootify and define user tables, roles and paths. This will give you your individual, executable prototype in just a few moments.

See Pricing
or read quickstart