Spring Security
Securing the Catalog and Order Service
The objective of this exercise is to secure the catalog and order microservices using JSON web tokens for authentication.
Add the
spring-boot-starter-security
and
spring-security-oauth2-jose
dependencies to the Maven configurations of the microservices.
Authentication Provider
Implement a
JwtAuthenticationProvider
class that implements the
AuthenticationProvider interface:
-
the
supports
method indicates that the provider only supports authentication tokens of type JwtAuthenticationToken
-
the
authenticate
method verifies a JwtAuthenticationToken
using the JwtTokenVerifier helper class and returns an authenticated token or throws an exception
Authentication Filter
Implement a
JwtAuthenticationFilter
class that extends the
OncePerRequestFilter:
- Provide a constructor to inject an authentication manager
-
Override the
doFilterInternal
method as follows:
- check if there is an authorization request header with scheme Bearer
- create a
JwtAuthenticationToken
with the corresponding token
- authenticate the
JwtAuthenticationToken
using the injected authentication manager
- if the authentication succeeds, populate the security context with the authenticated token and save it to a RequestAttributeSecurityContextRepository, otherwise clear the security context
Security Configuration
Implement a configuration class
SecurityConfig
that provides the following bean methods:
-
authenticationManager
creates an authentication manager with the JwtAuthenticationProvider
added to it
-
securityFilterChain
configures the HttpSecurity such that
- the CSRF token is disabled
- the
JwtAuthenticationFilter
is added to the filter chain
- an entry point is defined that returns the status code 401 if authentication fails
- the access to the REST endpoints is restricted as specified by the security requirements
- no sessions are used
and returns the corresponding SecurityFilterChain
Data Access
- When a customer registers, retrieve his username from the authentication token and store it with the customer's other data
- Use the saved username to ensure that a customer can only access his own data using one of the following options:
- In the methods of the customer and order service, check the data access programmatically by retrieving the role and name of the authenticated user from the security context
- Enable method security and annotate the service methods with appropriate method security expressions
- Add the
spring-security-data
dependency and use query security expressions in the customer and order repositories
- Ensure that employees can access all customer data.
Testing
Implement tests using the
MockMvc
bean and
security test annotations to verify the required security constraints.