Spring Boot Authorization with Spring Security
Add Spring Security to a Spring Boot app and control who reaches which endpoint: the dependency, the security configuration, and role-based rules.
First, you’ll need to add the Spring Security dependency to your project. You can do this by adding the following to your “pom.xml” file:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.4.4</version>
</dependency>Next, you’ll need to add a “WebSecurityConfigurerAdapter” to your project and override the “configure” method. This is where you’ll configure the rules for securing your app:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}This configuration will require that all requests to your app are authenticated using either a form login or HTTP basic authentication.
You can also specify more granular rules for which paths are secured and which are not by using the “antMatchers” method. For example:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();}
This configuration will require that all requests to paths starting with /admin/ have the role ADMIN, all requests to paths starting with /user/ have either the USER or ADMIN role, and all other requests are authenticated.
I hope this helps! Let me know if you have any other questions.
Authorization assumes you already know who the caller is. If that part is not in place yet, start with Spring Boot JWT Authentication, which builds the token filter this configuration sits on top of.
AuraLyrics
If you listen to music while you write code, AuraLyrics puts the lyrics over your editor instead of behind another window.
brew install --cask ozcberkay/tap/auralyricsNotes like this one, once a month
Java, AWS and what shipping a side product actually costs.