liveBook · Manning

authorizeHttpRequests

As explained in Spring Security in Action, Second Edition

authorizeHttpRequests is an HttpSecurity configuration method for defining authorization rules for HTTP requests.

authorizeHttpRequests is an HttpSecurity configuration method for defining authorization rules at the HTTP endpoint level. Pair it with an authentication mechanism such as HTTP Basic, then specify whether matching requests are open, authenticated, or restricted by authorities. section 2.3.2

Common authorization rules include:

  • anyRequest() applies the following rule to every request, regardless of URL or HTTP method. section 7.1.1
  • permitAll() allows matched requests without authentication. section 2.3.2
  • authenticated() requires the request to be authenticated. section 2.3.2
  • hasAuthority() permits users with one named authority, while hasAnyAuthority() accepts any authority from the supplied list. section 7.1.1
  • access() evaluates an authorization expression, such as requiring WRITE authority or combining read and delete checks. section 7.1.1

Restrict every endpoint by authority

Configure HTTP Basic authentication and require WRITE authority for every request: http.authorizeHttpRequests(c -> c.anyRequest().hasAuthority("WRITE")); A user with WRITE receives the endpoint response, while an authenticated user without it receives HTTP 403 Forbidden. section 7.1.1

Listing 2.7 Using the HttpSecurity parameter to alter the configuration
@Configuration
public class ProjectConfig {
  
  @Bean
  SecurityFilterChain configure(HttpSecurity http) 
    throws Exception {

    http.httpBasic(Customizer.withDefaults());      #1

    http.authorizeHttpRequests(
      c -> c.anyRequest().authenticated()           #2
    );

    return http.build();  
  }

  // Omitted code
  
}

See the complete SecurityFilterChain configuration using HttpSecurity, HTTP Basic, authorizeHttpRequests, authenticated(), and the Customizer lambda. section 2.3.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains open, authenticated, authority-based, and expression-based rules through runnable endpoint examples.
Examples
Uses a /hello endpoint with John and Jane to demonstrate permitAll, WRITE authority, multiple authorities, and HTTP 403 responses.
What you can do after
Apply it via Spring Security to configure public, authenticated, authority-based, or expression-based HTTP access.
How it connects
Connects HttpSecurity, SecurityFilterChain, HTTP Basic authentication, Customizer, user authorities, and authorization expressions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.