Introduction
Authorization controls what users can do in an app. It keeps private data safe and stops people from doing things they shouldn't.
Jump into concepts and practice - no test required
Authorization controls what users can do in an app. It keeps private data safe and stops people from doing things they shouldn't.
http.authorizeHttpRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated();hasRole for single roles and hasAnyRole for multiple roles.http.authorizeHttpRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated();http.authorizeHttpRequests()
.requestMatchers("/profile/**").authenticated()
.anyRequest().permitAll();This Spring Boot security config sets authorization rules. Admin pages need ADMIN role. User pages need USER or ADMIN. All other pages require login. It also enables a login form.
import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests() .requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated() .and() .formLogin(); return http.build(); } }
Authorization is different from authentication. Authentication checks who you are; authorization checks what you can do.
Always test your authorization rules to avoid accidental data leaks.
Authorization controls user access to app features and data.
Use Spring Security to set role-based access rules easily.
Proper authorization keeps your app safe and trustworthy.
/admin/dashboard?
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated();
}@Secured("USER")
public String getUserData() {
return "data";
}http.authorizeRequests()
.antMatchers("/sensitive/**").hasAnyRole("ADMIN", "MANAGER")
.anyRequest().authenticated();
B) http.authorizeRequests()
.antMatchers("/sensitive/**").hasRole("ADMIN")
.antMatchers("/sensitive/**").hasRole("MANAGER")
.anyRequest().authenticated();
C) http.authorizeRequests()
.antMatchers("/sensitive/**").permitAll()
.anyRequest().authenticated();
D) http.authorizeRequests()
.antMatchers("/sensitive/**").denyAll()
.anyRequest().authenticated();