FC
FACADE
CODE
Lesson 6 of 28
FC
FACADE
CODE

Learn Spring Security

Contents

01. Bootstrap The Application
1. Introduction
2. Install Spring Security
3. Enable Basic Auth
4. Authentication with AppUser
5. Password Encoder
02. Web Layer Security - RBAC
6. Permit Public APIs
7. Role Based Authorization
8. Disable CSRF
9. Current Authenticated User
03. Web Layer Security - PBAC
10. Permission Based Authorization
11. Define Permissions
12. Assign Permissions
13. Remove Role Based Access
04. Service Layer Security
14. PreAuthorize
15. PostAuthorize
16. Authorize Using Spring Beans
05. Domain Object Instance Security
17. Domain Object Instance Security
18. PermissionEvaluator Interface
19. PermissionEvaluator Strategy
20. DB Backed UserDetailsService
06. Token Based Authentication
21. Basic Authentication Revisited
22. Generate Token
23. Persist Token
24. Verify Token
25. Invalidate Token
07. Token Based Authentication and Authorization
26. JSON Web Token
27. Generate JWT
28. Verify JWT

Permit Public APIs

We are now aware that the default behaviour of Spring Security secures all the resources. In addition we have configured HttpSecurity to authenticate any HTTP requests using Basic Auth. This enforced us to provide username and password everytime we access an API in order to authenticate ourselves, failing to provide them resulted in 401 Unauthorized error.

However, ListCourses and GetCourse APIs are open for anyone to access without authentication. In this chapter we will relax the access restriction for these APIs using antMatchers().

First let's add the Public API urls in a constant class like below:


public class SecurityConstants {
    public static final String API_LIST_COURSES = "/api/v1/courses";
    public static final String API_GET_COURSE = "/api/v1/courses/*";

    public static final String[] PUBLIC_API_LIST = new String[] {
        API_LIST_COURSES,
        API_GET_COURSE
    };
};

AntMatchers

antMatchers() are overloaded methods to configure restrictions for specific urls matching the provided antPattern urls. We can either chain them together with authorizeRequests() or pass it as an argument to the authorizeRequests() in the form of lambda expression.

Here we are going to use one of the overloaded methods which accepts both HttpMethod and antPattern urls: antMatchers(HttpMethod, String...)

      
@Configuration
public class ApiSecurityConfig {
    @Bean
    public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(auth -> auth
                .antMatchers(GET, PUBLIC_API_LIST).permitAll()
                .anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }
} 

As ListCourses and CreateCourse endpoints are the same but with different HttpMethod, we have to specify HttpMethod.GET in the antMatchers to permit only the ListCourses API.

The order in which the antMatchers are defined is important, with most restricted resources defined at the top followed by least restricted resources at the bottom.

Test Public APIs

Restart the application and access the two Public APIs from Postman by selecting No Auth option in the Authorization tab. With No Auth we are not required to provide username and password. And we can notice the APIs returning the expected response with no authentication required anymore.

List of courses returned with No Auth
List of courses returned with No Auth