Lesson 3: URL Authorization

Note: There is an Errata section below for this video.

1. Main Goal

The goal of this lesson is to explain the basics of URL Authorization.


2. Lesson Notes

The relevant module you need to import when you're starting with this lesson is: lssc-module1/m1-lesson3

If you want to skip and see the complete implementation, feel free to jump ahead and import: lssc-module1/m1-lesson4

The credentials used in the code of this lesson are: user/pass (in memory).


2.1. URL Authorization

Starting from our previous security config, we are going to override the following:

@Override
protected void configure(HttpSecurity http) throws Exception { 
    http
      .authorizeRequests().anyRequest().authenticated()
      .and().formLogin()
      .and().httpBasic();
}

Notice that this is actually the default implementation of this method - which we are going to copy and use as a good starting point.

We can change this by adding some extra configuration for the delete operation:

.antMatchers("/delete/**").hasRole("ADMIN")

Finally, we're going to look at a few examples using:

  • hasAuthority
  • hasAnyRole
  • hasAnyAuthority

And briefly mention:

  • hasIpAddress
  • access
  • anonymous
  • denyAll, permitAll
  • fullyAuthenticated, rememberMe


2.2. Upgrade Notes

With Boot 3 / Spring Security 6, the whole authorization mechanism is being replaced in favor of an AuthorizationManager-based solution, and all the old authorization instruments have been deprecated.

So, with the new version, we have to replace the now deprecated authorizeRequests usages for the new authorizeHttpRequests method (which is used to opt-in to the AuthorizationManager-based mechanism).

Similarly, the antMatchers and mvcMatchers methods were deprecated in favor of using requestMatchers.

The new way of setting up the HttpSecurity in the security config class is as follows:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((requests) -> requests
            .requestMatchers("/delete/**").hasRole("ADMIN")
            .anyRequest().authenticated())
        .formLogin(Customizer.withDefaults());
    return http.build();
}


2.3. Errata

Note that there is a known problem in the video - the general anyRequest() and the more specific .antMatchers("/delete/**") - should be in the reverse order (the more specific first, the more general last).


3. Resources

- Spring Security Reference - Authorization


LSS - URL Authorization - transcript.pdf
Complete and Continue