FC
FACADE
CODE
Lesson 3 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

Enable Basic Authentication

Basic Auth is an authentication mechanism for any HTTP user agents like browser or REST clients like Postman to provide username and password when making a request. It is stateless where each request must contain Authorization header with value in the format Basic <Credentials>, where Credentials is the base64 encoding of username and password joined by a single colon (username:password).

Configure HttpSecurity

We can customise the Spring Security behaviour to use only Basic Authentication and ignore form based login. We can do so by configuring web based security for all http requests using HttpSecurity. We will then use it to build and register SecurityFilterChain bean inside a @Configuration class as below:


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

Here we have configured HttpSecurity to authenticate any request using Basic Auth. It might sound like the default behaviour we saw earlier. But configuring HttpSecurity explicitly with httpBasic() tells Spring Security to choose only BasicAuthenticationEntryPoint as the default EntryPoint and ignore LoginUrlAuthenticationEntryPoint.

Restart the application and access the ListCourses API from the browser. It will respond with 401 Unauthorised instead of 302 Found redirect error status. Also it will enable the browser to stay on the same page and prompt us for username and password rather than redirecting to login page. Once we enter the credentials we can see the list of courses.

Browser prompting for username and password
Browser prompting for username and password
List of courses returned for the entered credentials
List of courses returned for the entered credentials