Last updated: 2024-06-29
Basic Authentication with Spring Boot
Spring Security provides a powerful framework to authenticate users and protect our application against further threats. How can we add basic authentication to our Spring Boot app? At the end a library is introduced to fully protect individual instances without breaking an existing setup.
Spring Security setup
To implement basic auth with Spring Security, we first add the Spring Boot Starter org.springframework.boot:spring-boot-starter-security
as a depdenciy. Now our configuration could look like this in its simplest form.
Essential setup for Basic Auth
The configured SecurityFilterChain
applies to the entire application and now requires authentication using basic auth for every request. The UserDetailsService
found in the application context is automatically picked up so that we can log in with the user name "user"
and the password "Bootify!"
- here provided as a bcrypt encrypted value.
The browser now automatically asks for credentials as soon as we open our application. All further security mechanisms of Spring Security are active in their default settings. To further refine our configuration, the following setup provides a good starting point.
Further refinement of our configuration
With this adjustment, basic authentication is only required for the paths below /api/**
. Since our REST API is located there, we can deactivate CSRF, which would only be relevant for server-side rendering. We have also specified an explicit real name overwriting the default.
When using the method hasAuthority(...)
instead of hasRole(...)
, the prefix "ROLE_"
must be provided explicitly - this way we also avoid any confusion.
Protect the entire application
Sometimes you want to protect the entire application with basic auth, for example to make a staging or development instance inaccessible from the outside. This is only possible with Spring Security if no further authentication mechanisms are used. "Double authentication" of a single path, e.g. with basic auth and form-based login, is not supported.
The Springify Basicauth library could be used for this scenario. This allows basic authentication to be enabled for certain profiles without interfering with any existing setup of Spring Security.
Bring back the fun to Spring Security! Bootify allows to create complex security setups with basic authentication, form login and much more in the Professional Plan. You can explicitly specify roles and which parts of the application they are allowed to access.
See Pricing
or read quickstart