Skip to content

Latest commit

 

History

History
221 lines (181 loc) · 8.26 KB

File metadata and controls

221 lines (181 loc) · 8.26 KB

Lab 11: Security with Spring Security and OAuth 2.0

Objective

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.


Steps

1. Create an Authorization Server

  • In MicroservicesProject, create a new folder named AuthServer for the authorization server.

2. Generate Authorization Server with Spring Initializr

  • 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.
  • Save the project in the AuthServer folder.

3. Configure Authorization Server Properties

  • In AuthServer/src/main/resources, open application.properties and add the following configuration:
    server.port=9000
    spring.application.name=auth-server

4. Set Up Authorization 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);
        }
    }

5. Configure In-Memory Clients for Testing

  • 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);
        }
    }

6. Configure Resource Server in Each Microservice

  • For each service (UserService, ProductService, OrderService), open pom.xml.
  • Add the OAuth2 Resource Server dependency:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>

7. Add Security Configuration to Each Microservice

  • 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();
        }
    }

8. Configure OAuth2 Properties in Each Microservice

  • 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

9. Add Roles and Authorization in Auth Server

  • 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
        }
    }

10. Test Authorization with Postman

  • Open Postman and follow these steps:
    1. Request Token: Create a POST request to http://localhost:9000/oauth/token with the following body:
      grant_type=password
      client_id=client-id
      client_secret=client-secret
      username=user
      password=password
      
    2. 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).

11. Verify Access Control with Roles

  • 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");
        }
    }

12. Test Role-Based Access in Postman

  • 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.

13. Containerize Auth Server with Docker

  • In the AuthServer directory, create a Dockerfile:

    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 .

14. Update Docker Compose for Auth Server

  • In the MicroservicesProject directory, open docker-compose.yml.
  • Add the Auth Server configuration:
    auth-server:
      build: ./AuthServer
      ports:
        - "9000:9000"

15. Update Microservices to Use Dockerized Auth Server

  • 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

16. Run Docker Compose

  • Start all services, including Auth Server, with Docker Compose:
    docker-compose up -d

17. Test Secured Endpoints with Dockerized Auth Server

  • Use Postman to request a token from the Dockerized Auth Server and verify that the microservices enforce security based on the received token.

18. Summary of Lab

  • 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.

Extra Exercise (20 minutes)

  1. Create Additional Roles and Permissions:

    • Add an ADMIN role in the authorization server and secure an endpoint in ProductService to allow only ADMIN users.
    • Test the ADMIN access in Postman.
  2. 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.
  3. Enable CSRF Protection:

    • Enable CSRF protection in each microservice’s security configuration and test CSRF tokens in requests.