Set up security across UserService
, ProductService
, and OrderService
using Spring Security and OAuth 2.0. This will enable secure access to microservices by requiring authentication and role-based authorization.
- In MicroservicesProject, create a new folder named
AuthServer
for the authorization server.
- Open the Command Palette (View > Command Palette or
Ctrl+Shift+P
). - Select Spring Initializr: Generate a Maven Project.
- Configure the options as follows:
- Group Id:
com.microservices
- Artifact Id:
auth-server
- Name:
AuthServer
- Add dependencies: Spring Security, OAuth2 Authorization Server, and Spring Web.
- Group Id:
- Save the project in the
AuthServer
folder.
- In
AuthServer/src/main/resources
, openapplication.properties
and add the following configuration:server.port=9000 spring.application.name=auth-server
- In
AuthServerApplication.java
, configure the authorization server:package com.microservices.authserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AuthServerApplication { public static void main(String[] args) { SpringApplication.run(AuthServerApplication.class, args); } }
- Create a configuration class
AuthorizationServerConfig.java
to configure OAuth 2.0 clients:package com.microservices.authserver.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; @Configuration public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client-id") .secret("{noop}client-secret") .authorizedGrantTypes("password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(3600); } }
- For each service (
UserService
,ProductService
,OrderService
), openpom.xml
. - Add the OAuth2 Resource Server dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
- In each service, create a class
ResourceServerConfig.java
with security configurations:package com.microservices.common.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/public/**").permitAll() .antMatchers("/api/**").authenticated(); } }
- In each microservice’s
application.properties
, add properties to use the authorization server:spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:9000/oauth/token
- In
AuthorizationServerConfig.java
, configure roles for users:import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfigurer; @Configuration public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // Configure user roles and token endpoints here } }
- Open Postman and follow these steps:
- Request Token: Create a
POST
request tohttp://localhost:9000/oauth/token
with the following body:grant_type=password client_id=client-id client_secret=client-secret username=user password=password
- Use Token: Copy the access token from the response and add it to the Authorization header in requests to other services (e.g.,
UserService
,ProductService
,OrderService
).
- Request Token: Create a
- In
UserService
, configure an endpoint with role-based access:package com.microservices.userservice; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @PreAuthorize("hasRole('ROLE_USER')") @GetMapping("/api/users/{id}") public User getUserById(@PathVariable Long id) { // method logic return new User(id, "John Doe"); } }
- Use Postman to access the secured endpoint with a token from an authenticated user.
- Verify that users without the appropriate role cannot access restricted endpoints.
-
In the
AuthServer
directory, create aDockerfile
:FROM openjdk:17 EXPOSE 9000 ADD target/auth-server.jar auth-server.jar ENTRYPOINT ["java", "-jar", "auth-server.jar"]
-
Build the Docker image for Auth Server:
docker build -t auth-server .
- In the MicroservicesProject directory, open
docker-compose.yml
. - Add the Auth Server configuration:
auth-server: build: ./AuthServer ports: - "9000:9000"
- Modify each service’s
application.properties
to point to the Dockerized Auth Server:spring.security.oauth2.resourceserver.jwt.issuer-uri=http://auth-server:9000/oauth/token
- Start all services, including Auth Server, with Docker Compose:
docker-compose up -d
- Use Postman to request a token from the Dockerized Auth Server and verify that the microservices enforce security based on the received token.
- Review what was covered:
- Set up an OAuth 2.0 Authorization Server.
- Configured microservices as OAuth Resource Servers.
- Implemented role-based access and verified security with OAuth tokens.
-
Create Additional Roles and Permissions:
- Add an
ADMIN
role in the authorization server and secure an endpoint inProductService
to allow onlyADMIN
users. - Test the
ADMIN
access in Postman.
- Add an
-
Implement Token Expiry Handling:
- Set up short expiration times for access tokens.
- Use Postman to simulate token expiration and test token refresh using
refresh_token
grant type.
-
Enable CSRF Protection:
- Enable CSRF protection in each microservice’s security configuration and test CSRF tokens in requests.