API Gateway এবং Client-Side Security মাইক্রোসার্ভিস আর্কিটেকচারে অত্যন্ত গুরুত্বপূর্ণ। API Gateway একটি মিডলওয়্যার হিসেবে কাজ করে, যা বিভিন্ন সার্ভিসের সাথে ক্লায়েন্টের যোগাযোগ পরিচালনা করে, এবং Client-Side Security আপনার ক্লায়েন্ট অ্যাপ্লিকেশনের নিরাপত্তা নিশ্চিত করে। নিচে উল্লিখিত বিষয়গুলোর বিশদ বর্ণনা দেওয়া হলো।
API Gateway
API Gateway হলো একটি সার্ভিস, যা ক্লায়েন্ট থেকে সমস্ত রিকোয়েস্ট গ্রহণ করে এবং সেগুলি সার্ভিসে পাঠানোর কাজ করে। এটি একাধিক মাইক্রোসার্ভিসের জন্য একটি একক এন্ট্রি পয়েন্ট হিসাবে কাজ করে।
API Gateway এর কাজ:
- Request Routing: ক্লায়েন্টের রিকোয়েস্ট যথাযথ সার্ভিসে পাঠানো।
- Load Balancing: সার্ভিসগুলোর মধ্যে লোড সমানভাবে বিতরণ করা।
- Authentication and Authorization: নিরাপত্তা চেক করা এবং নিশ্চিত করা যে ক্লায়েন্টের কাছে অনুমতি আছে কিনা।
- Rate Limiting: API কলের সীমা নির্ধারণ করা।
- Logging and Monitoring: রিকোয়েস্ট এবং রেসপন্স মনিটর করা।
Spring Cloud Gateway (API Gateway) ব্যবহার
Spring Boot অ্যাপ্লিকেশনে API Gateway হিসেবে Spring Cloud Gateway ব্যবহার করা হয়।
Spring Cloud Gateway ডিপেন্ডেন্সি:
Maven pom.xml-এ Spring Cloud Gateway এর ডিপেন্ডেন্সি যোগ করুন:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
API Gateway Configuration:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.cloud.gateway.config.GlobalFilter;
import org.springframework.cloud.gateway.filter.GlobalFilterChain;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.web.server.ServerWebExchange;
@Configuration
public class GatewayConfig {
@Bean
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
@Bean
public GatewayFilter customFilter() {
return new GatewayFilter() {
@Override
public org.springframework.web.server.WebFilter.FilterChain filter(ServerWebExchange exchange, org.springframework.web.server.WebFilter.FilterChain chain) {
// Your custom logic here
return chain.filter(exchange);
}
};
}
}
application.yml Configuration:
Spring Cloud Gateway এর configuration application.yml বা application.properties ফাইলে করতে পারেন।
spring:
cloud:
gateway:
routes:
- id: myservice
uri: lb://my-service
predicates:
- Path=/my-service/**
filters:
- AddRequestHeader=X-Request-Foo, Bar
এই কনফিগারেশনে lb:// স্কিমা Load Balancer ব্যবহার করে এবং Path অনুযায়ী রিকোয়েস্ট গাইড করবে।
Client-Side Security
Client-Side Security মূলত ক্লায়েন্ট অ্যাপ্লিকেশনের সুরক্ষা ব্যবস্থা যেমন Authentication, Authorization, Encryption, এবং Session Management নিয়ে কাজ করে।
Client-Side Security কৌশলগুলি:
- Authentication (ব্যবহারকারীর প্রমাণীকরণ):
- Token-Based Authentication (যেমন JWT) ব্যবহার করে ব্যবহারকারীর প্রমাণীকরণ নিশ্চিত করা হয়।
- Spring Security ব্যবহার করে ক্লায়েন্ট থেকে সার্ভারে JWT টোকেন প্রেরণ করা হয় এবং সেগুলি যাচাই করা হয়।
- Authorization (অধিকার যাচাই):
- ক্লায়েন্ট অ্যাপ্লিকেশন, সার্ভিসের নির্দিষ্ট রিসোর্সে অ্যাক্সেস পাওয়ার জন্য প্রয়োজনীয় অনুমতি যাচাই করে।
- Spring Security OAuth2 বা JWT ব্যাবহার করা যেতে পারে।
- HTTPS (SSL/TLS):
- HTTPS প্রোটোকল ব্যবহার করে ক্লায়েন্ট-সার্ভারের মধ্যে ডেটা এনক্রিপশন করা হয়, যাতে কোনো তৃতীয় পক্ষের কাছে ডেটা ফাঁস না হয়।
- Cross-Site Request Forgery (CSRF):
- CSRF আক্রমণ থেকে রক্ষা পেতে Spring Security-তে CSRF সুরক্ষা চালু করতে হয়।
- Cross-Origin Resource Sharing (CORS):
- CORS কনফিগারেশন ক্লায়েন্ট অ্যাপ্লিকেশনের নিরাপত্তা নিশ্চিত করে বিভিন্ন ডোমেইন থেকে রিকোয়েস্ট গ্রহণ করতে।
Spring Boot Client-Side Security উদাহরণ:
JWT Token Authentication উদাহরণ:
Spring Boot API থেকে JWT টোকেন প্রাপ্ত করার জন্য নিম্নলিখিত কনফিগারেশন করতে হবে:
- JWT Token Filter (Custom Filter):
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.util.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private String jwtSecretKey = "secretKey"; // Your JWT Secret Key
@Override
protected void doFilterInternal(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String jwtToken = getJwtFromRequest(request);
if (StringUtils.hasText(jwtToken) && validateToken(jwtToken)) {
Authentication authentication = getAuthentication(jwtToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
private boolean validateToken(String token) {
// Validate JWT Token here (use libraries like jjwt or io.jsonwebtoken)
return true; // Example: Assume token is valid
}
private Authentication getAuthentication(String token) {
// Create and return the Authentication object based on the token
return new UsernamePasswordAuthenticationToken("user", null, new ArrayList<>());
}
}
- Spring Security Configuration:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login", "/public/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JwtAuthenticationFilter());
}
}
- Client-Side JWT Authentication Request:
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
public class AuthClient {
public static void main(String[] args) {
String token = "your-jwt-token-here";
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/protected-endpoint";
String response = restTemplate.getForObject(url, String.class, headers);
System.out.println(response);
}
}
CORS Configuration for Security:
Spring Security এর মাধ্যমে CORS কনফিগারেশন করতে পারেন যাতে একটি সিকিউর ক্লায়েন্ট এবং সার্ভারের মধ্যে সঠিকভাবে রিকোয়েস্ট ট্রান্সফার হয়।
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000") // Allowed client-side origins
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
উপসংহার:
- API Gateway: Spring Cloud Gateway বা অন্য API Gateway-এর মাধ্যমে সার্ভিসগুলি একীভূত করে ক্লায়েন্টের জন্য সহজ এবং নিরাপদ এক্সেস প্রদান করা যায়।
- Client-Side Security: JWT, HTTPS, CSRF, CORS এবং OAuth2 ব্যবহারের মাধ্যমে ক্লায়েন্ট অ্যাপ্লিকেশনের নিরাপত্তা নিশ্চিত করা যায়।
এই দুটি বিষয় মাইক্রোসার্ভিস আর্কিটেকচারে অপরিহার্য, কারণ এটি আপনার অ্যাপ্লিকেশনের সুরক্ষা এবং স্কেলেবিলিটি নিশ্চিত করে।
API Gateway হল একটি সার্ভিস যা একাধিক ব্যাকএন্ড সার্ভিসের জন্য একক পয়েন্ট হিসেবে কাজ করে। এটি বিভিন্ন মাইক্রোসার্ভিসে থাকা API গুলির রিকোয়েস্ট এবং রেসপন্সগুলিকে কেন্দ্রীয়ভাবে পরিচালনা করে। API Gateway এর মাধ্যমে আমরা সার্ভিস রিকোয়েস্ট গুলি সেন্ট্রালাইজড ও একত্রিতভাবে পরিচালনা, মনিটরিং এবং সিকিউরিটি নিশ্চিত করতে পারি।
API Gateway এর ধারণা:
API Gateway হল একটি আর্কিটেকচারাল প্যাটার্ন যা মাইক্রোসার্ভিস অ্যাপ্লিকেশনের জন্য খুবই উপকারী। এটি এক বা একাধিক ব্যাকএন্ড সার্ভিসে আগত রিকোয়েস্টগুলিকে রাউট, রিজেক্ট বা প্রসেস করতে সাহায্য করে। API Gateway মূলত Client এবং Microservices এর মধ্যে ব্রোকার হিসেবে কাজ করে।
API Gateway এর কাজের প্রক্রিয়া:
১. রিকোয়েস্ট গ্রহণ:
API Gateway প্রথমে ক্লায়েন্ট (যেমন: ওয়েব ব্রাউজার, মোবাইল অ্যাপ্লিকেশন) থেকে একটি HTTP রিকোয়েস্ট গ্রহণ করে।
২. রিকোয়েস্ট প্রক্রিয়াকরণ:
API Gateway রিকোয়েস্টের ওপর বিভিন্ন ধরনের কাজ করতে পারে:
- Routing: কোন মাইক্রোসার্ভিসে রিকোয়েস্টটি পাঠাতে হবে তা সিদ্ধান্ত নেওয়া।
- Authentication & Authorization: API Gateway ক্লায়েন্টের অ্যাক্সেস নিশ্চিত করার জন্য সিকিউরিটি চেক করে।
- Load Balancing: রিকোয়েস্টগুলো সঠিকভাবে বিভিন্ন সার্ভিস ইনস্ট্যান্সে বিলি করা।
- Request Transformation: রিকোয়েস্টের ডাটা ফরম্যাট পরিবর্তন করা (যেমন JSON to XML বা vice versa)।
- Caching: প্রাথমিক ফলাফল ক্যাশে করে রাখা।
- Rate Limiting: একসাথে বেশি রিকোয়েস্ট আসা প্রতিরোধ করতে সীমাবদ্ধতা আরোপ করা।
৩. ব্যাকএন্ড সার্ভিসে রিকোয়েস্ট পাঠানো:
API Gateway উপরের কাজগুলো করার পর, ব্যাকএন্ড মাইক্রোসার্ভিসগুলোর মধ্যে নির্দিষ্ট সার্ভিসে রিকোয়েস্ট রিডাইরেক্ট করে।
৪. রেসপন্স সংগ্রহ এবং ফেরত পাঠানো:
যখন ব্যাকএন্ড সার্ভিস থেকে রেসপন্স আসে, API Gateway রেসপন্সটি ক্লায়েন্টকে পাঠায়। এছাড়াও, API Gateway রেসপন্সের ওপর কিছু অতিরিক্ত কাজ করতে পারে (যেমন ডাটা ট্রান্সফরমেশন বা ক্যাশিং)।
৫. রিলেসমেন্ট, মোনিটরিং এবং লগিং:
API Gateway এর মাধ্যমে সার্ভিসগুলির মধ্যে ট্র্যাফিক মনিটরিং এবং লগিং করা যায়। এর মাধ্যমে সার্ভিসের স্বাস্থ্য পর্যবেক্ষণ, লেটেন্সি, এবং ব্যান্ডউইথ ব্যবহারের তথ্য পাওয়া যায়।
API Gateway এর প্রধান সুবিধা:
- Centralized Management:
- সমস্ত মাইক্রোসার্ভিসের জন্য একক পয়েন্ট হিসেবে কাজ করে। এক জায়গায় সব API রাউটিং এবং সিকিউরিটি কনফিগারেশন করা যায়।
- Security:
- ক্লায়েন্টের সাথে ব্যাকএন্ড সার্ভিসের মধ্যে সিকিউরিটি নিশ্চিত করতে পারে (OAuth, JWT, API Keys ইত্যাদি)।
- Load Balancing:
- API Gateway রিকোয়েস্টগুলোকে সার্ভিস ইনস্ট্যান্সের মধ্যে সঠিকভাবে ভারসামিত করতে সাহায্য করে।
- API Versioning:
- API Gateway এর মাধ্যমে API ভার্সন কন্ট্রোল করা সম্ভব। একাধিক API ভার্সন একই সময়ে কাজ করতে পারে।
- Caching:
- API Gateway সাধারণত কিছু ফিক্সড রেসপন্স ক্যাশে করে রাখতে পারে, যাতে সার্ভিসের প্রতি রিকোয়েস্টের সময় কমানো যায়।
- Rate Limiting:
- ক্লায়েন্টকে নির্দিষ্ট সংখ্যক রিকোয়েস্টে সীমাবদ্ধ রাখা যায়।
Spring Boot API Gateway: Spring Cloud Gateway
Spring Cloud Gateway হল Spring Framework এর একটি প্রকল্প যা API Gateway হিসেবে কাজ করতে পারে। এটি non-blocking, reactive ভিত্তিতে কাজ করে এবং API Gateway তৈরি করতে খুবই সুবিধাজনক।
Spring Cloud Gateway এর ফিচারসমূহ:
- Routing: URL প্যাটার্ন অনুযায়ী রিকোয়েস্ট রাউটিং।
- Filters: রিকোয়েস্ট এবং রেসপন্সে ফিল্টার অপারেশন।
- Load Balancing: সার্ভিস ইনস্ট্যান্সের মধ্যে লোড ব্যালেন্সিং।
- Security: Spring Security ইন্টিগ্রেশন।
- Rate Limiting: রিকোয়েস্টের জন্য নির্দিষ্ট সীমা নির্ধারণ।
- Circuit Breaker: রিকোয়েস্ট ফেইল হলে সার্ভিসে সার্কিট ব্রেকার প্রয়োগ।
Spring Cloud Gateway সেটআপ:
১. ডিপেনডেন্সি যোগ করুন:
Spring Cloud Gateway ব্যবহার করতে নিচের ডিপেনডেন্সি যুক্ত করুন।
Maven:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
Gradle:
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
২. API Gateway কনফিগারেশন:
application.yml ফাইলে API Gateway কনফিগার করা যায়।
spring:
cloud:
gateway:
routes:
- id: myService
uri: lb://my-service-name
predicates:
- Path=/api/**
filters:
- AddRequestHeader=X-Request-Foo, Bar
- uri: ব্যাকএন্ড সার্ভিসের URL (এখানে লোড ব্যালান্সিং করা হচ্ছে)।
- predicates: রাউটিং কন্ডিশন, যেমন
Path,Host,Method, ইত্যাদি। - filters: রিকোয়েস্ট বা রেসপন্সের ওপর ফিল্টার প্রয়োগ করা।
৩. রাউটিং কনফিগারেশন:
Spring Cloud Gateway ব্যবহার করে API গুলিকে সহজেই রাউট করতে পারেন।
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/get")
.uri("http://httpbin.org:80"))
.route(r -> r.host("*.circuitbreaker.com")
.filters(f -> f.circuitBreaker(c -> c.setName("mycmd")
.setFallbackUri("forward:/fallback")))
.uri("http://httpbin.org:80"))
.build();
}
}
API Gateway এর সাধারণ ব্যবহার:
- Frontend API: একাধিক ব্যাকএন্ড সার্ভিসের জন্য একক API পয়েন্ট হিসেবে ব্যবহার করা।
- Authentication: ক্লায়েন্ট সিকিউরিটি যাচাই করার জন্য সিঙ্গল পয়েন্ট হিসেবে কাজ করা।
- API Rate Limiting: সার্ভিসের অতিরিক্ত রিকোয়েস্ট সীমাবদ্ধ করার জন্য API Gateway ব্যবহার করা।
উপসংহার:
API Gateway হলো একটি গুরুত্বপূর্ণ উপাদান, যা মাইক্রোসার্ভিস আর্কিটেকচারে একাধিক সার্ভিসের মধ্যে যোগাযোগ ও রিকোয়েস্ট প্রক্রিয়াকরণ সহজ করে। Spring Cloud Gateway একটি শক্তিশালী এবং কনফিগারেবল API Gateway, যা Spring Boot অ্যাপ্লিকেশনগুলির জন্য আদর্শ সমাধান।
প্রয়োজন হলে আরও বিস্তারিত বা উদাহরণ জানতে বলুন! 😊
Spring Cloud Gateway হল একটি API গেটওয়ে, যা ক্লায়েন্ট-সাইড সিকিউরিটি এবং রুটিং টাস্কের জন্য ব্যবহৃত হয়। এটি আপনাকে বিভিন্ন সার্ভিসের উপর লোড ব্যালেন্সিং, সিকিউরিটি এবং রেট লিমিটিং সমর্থন সহ একটি কাস্টম গেটওয়ে সেটআপ করতে দেয়।
এই গেটওয়ে সাধারণত সার্ভিস-মেশ বা মাইক্রোসার্ভিস আর্কিটেকচারে ব্যবহৃত হয়। Spring Cloud Gateway-এ সিকিউরিটি ইন্টিগ্রেশন বিভিন্ন পদ্ধতিতে করা যেতে পারে, যেমন JWT (JSON Web Tokens), OAuth2, বা Basic Authentication। এই গেটওয়ে সার্ভিসে গেটওয়ে লেভেলে সিকিউরিটি নিশ্চিত করার পাশাপাশি ক্লায়েন্ট সাইডে সিকিউরিটি হ্যান্ডল করার জন্য কিছু কনফিগারেশন করা যায়।
Spring Cloud Gateway Setup
1. Spring Cloud Gateway Setup
প্রথমে, আপনার Spring Boot অ্যাপ্লিকেশনটি Spring Cloud Gateway হিসেবে কনফিগার করতে হবে।
ডিপেন্ডেন্সি যোগ করা:
pom.xml ফাইলে নিচের ডিপেন্ডেন্সি যোগ করুন:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
2. Gateway Configuration
application.yml বা application.properties ফাইলে Spring Cloud Gateway কনফিগারেশন করুন, যাতে API রুটিং এবং সিকিউরিটি সিস্টেম ঠিকভাবে কাজ করে।
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/users/**
filters:
- AddRequestHeader=X-Request-Foo, Bar
- AddResponseHeader=X-Response-Foo, Baz
# Example of security configuration
security:
oauth2:
client:
registration:
google:
client-id: YOUR-CLIENT-ID
client-secret: YOUR-CLIENT-SECRET
scope: profile, email
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
authorization-grant-type: authorization_code
client-name: Google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
এই কনফিগারেশনটি Spring Cloud Gateway-এ OAuth2-এর মাধ্যমে ক্লায়েন্ট সাইড সিকিউরিটি চালু করে, এবং গুগল OAuth2 প্রোভাইডার ব্যবহার করে ইউজারের লগইন এবং অথোরাইজেশন সেটআপ করে।
3. Spring Cloud Gateway with Client-Side Security Integration (OAuth2)
ক্লায়েন্ট-সাইড সিকিউরিটির জন্য, OAuth2 সিকিউরিটি ব্যবহার করার মাধ্যমে Spring Cloud Gateway অ্যাপ্লিকেশন সুরক্ষিত করা যেতে পারে। নিচে OAuth2 সিকিউরিটি ইন্টিগ্রেশন এর উদাহরণ দেওয়া হলো:
OAuth2 Client Setup
Spring Cloud Gateway ক্লায়েন্ট হিসেবে OAuth2 এর সাহায্যে API কলগুলির সিকিউরিটি নিশ্চিত করতে, OAuth2 Client Configuration করতে হয়। spring-security-oauth2-client ডিপেনডেন্সি যুক্ত করুন এবং application.yml ফাইলে সঠিক কনফিগারেশন দিন।
spring:
security:
oauth2:
client:
registration:
google:
client-id: YOUR-CLIENT-ID
client-secret: YOUR-CLIENT-SECRET
scope: profile, email
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
client-name: Google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
4. Spring Security Configuration with OAuth2
OAuth2LoginAuthenticationFilter ব্যবহার করে Spring Security এর সাহায্যে সিকিউরিটি কনফিগার করতে হবে। এই ফিল্টার ক্লায়েন্ট সাইডে সিকিউরিটি ভ্যালিডেশন করবে।
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Sso;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login/**", "/error", "/oauth2/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login(); // Enable OAuth2 login
return http.build();
}
}
এটি OAuth2 সিকিউরিটি সিস্টেম তৈরি করবে যা গুগল বা অন্য OAuth2 প্রোভাইডার দ্বারা অ্যাক্সেস কন্ট্রোল নিশ্চিত করবে।
5. API Gateway সিকিউরিটি: JWT (JSON Web Token)
Spring Cloud Gateway এর সাথে JWT ব্যবহার করে সিকিউরিটি ইন্টিগ্রেশন করার জন্য, আপনাকে কিছু ফিল্টার এবং স্ট্র্যাটেজি কনফিগার করতে হবে।
JWT Filter Creation:
একটি কাস্টম ফিল্টার তৈরি করুন যা JWT টোকেন যাচাই করবে এবং নিরাপদ API রিকোয়েস্ট অনুমোদন করবে।
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
@Component
public class JwtTokenFilter implements WebFilter {
private final JwtDecoder jwtDecoder;
public JwtTokenFilter(JwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
if (token != null && token.startsWith("Bearer ")) {
String jwtToken = token.substring(7);
Jwt jwt = jwtDecoder.decode(jwtToken); // Validate and decode JWT token
// Further processing can be done here, e.g., setting user details in SecurityContext
}
return chain.filter(exchange);
}
}
JWT Filter Integration in Gateway
এই ফিল্টারটি Spring Cloud Gateway এর রুট ফিল্টার হিসেবে যুক্ত করা যাবে। এইভাবে আপনি API গেটওয়ে লেভেলে সিকিউরিটি নিশ্চিত করতে পারবেন।
spring:
cloud:
gateway:
filters:
- name: JwtTokenFilter
6. Full Example (OAuth2 with Gateway)
application.yml-এ OAuth2 সেটআপ:
spring:
security:
oauth2:
client:
registration:
google:
client-id: YOUR-CLIENT-ID
client-secret: YOUR-CLIENT-SECRET
scope: profile, email
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
client-name: Google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/users/**
SecurityConfig.java:
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login/**", "/error", "/oauth2/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
return http.build();
}
}
উপসংহার
- Spring Cloud Gateway ব্যবহার করে ক্লায়েন্ট সাইড সিকিউরিটি ইন্টিগ্রেশন অনেক সহজ এবং কার্যকরী।
- OAuth2 বা JWT ব্যবহার করে গেটওয়ে লেভেলে নিরাপত্তা নিশ্চিত করা যায়।
- Spring Security-এর মাধ্যমে OAuth2 ক্লায়েন্ট সাইড সিকিউরিটি ইন্টিগ্রেশন সহজেই করা সম্ভব।
- JWT ফিল্টার ব্যবহার করে আপনার API গেটওয়ে লেভেলে নিরাপত্তা নিয়ন্ত্রণ এবং যাচাই করা যেতে পারে।
এইভাবে, Spring Cloud Gateway এর সাথে ক্লায়েন্ট-সাইড সিকিউরিটি ইন্টিগ্রেশন করতে পারেন, যা নিরাপদ এবং স্কেলেবল API গেটওয়ে প্রদান করবে।
স্প্রিং বুট ক্লায়েন্টে API Gateway এর মাধ্যমে Rate Limiting এবং Authentication কনফিগারেশন করার জন্য সাধারণত Spring Cloud Gateway এবং Spring Security ব্যবহার করা হয়। এটি মাইক্রোসার্ভিস আর্কিটেকচারে API গেটওয়ের মাধ্যমে রিকোয়েস্ট পরিচালনা এবং সুরক্ষা নিশ্চিত করতে সহায়তা করে।
১. Spring Cloud Gateway এর মাধ্যমে Rate Limiting এবং Authentication কনফিগারেশন
Spring Cloud Gateway একটি API গেটওয়ে হিসেবে কাজ করে এবং এটি Rate Limiting এবং Authentication পরিচালনা করতে সহায়ক। নিচে এর কনফিগারেশন দেয়া হলো।
২. Spring Cloud Gateway সেটআপ
২.১ ডিপেন্ডেন্সি যোগ করা
Maven:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Gradle:
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springframework.boot:spring-boot-starter-security'
২.২ Rate Limiting কনফিগারেশন
Spring Cloud Gateway এ Rate Limiting কনফিগার করতে Redis ব্যবহার করা হয়। এর মাধ্যমে নির্দিষ্ট সময়ের মধ্যে কতগুলো রিকোয়েস্ট অনুমোদিত হবে তা কনফিগার করা যায়।
application.yml ফাইলে Rate Limiting কনফিগারেশন:
spring:
cloud:
gateway:
routes:
- id: api_route
uri: http://example-service
predicates:
- Path=/api/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
redis-rate-limiter.requestedTokens: 1
redis:
host: localhost
port: 6379
replenishRate: প্রতি সেকেন্ডে কতগুলো টোকেন রিফিল হবে।burstCapacity: একসাথে সর্বোচ্চ কতগুলো রিকোয়েস্ট অনুমোদিত।requestedTokens: প্রতি রিকোয়েস্টের জন্য কতগুলো টোকেন প্রয়োজন।
২.৩ Authentication কনফিগারেশন
Spring Cloud Gateway এ Authentication সেটআপ করার জন্য Spring Security ব্যবহার করা হয়। সাধারণত JWT (JSON Web Token) এর মাধ্যমে Authentication এবং Authorization কনফিগার করা হয়।
২.৩.১ Spring Security কনফিগারেশন
SecurityConfig.java এ Spring Security কনফিগারেশন:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated() // Only authenticated users can access /api/**
.anyRequest().permitAll()
.and()
.oauth2Login(); // Using OAuth2 login
}
}
২.৪ JWT Authentication Integration
JWT ব্যবহার করে API Gateway এর মাধ্যমে Authentication কনফিগার করার উদাহরণ:
২.৪.১ JWT Filter
Spring Security তে JWT Authentication ফিল্টার যোগ করতে হবে যা গেটওয়ের জন্য সমস্ত রিকোয়েস্টকে যাচাই করবে।
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private static final String SECRET_KEY = "your_secret_key"; // Secret key for signing JWT
@Override
protected void doFilterInternal(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = request.getHeader("Authorization");
if (token != null && token.startsWith("Bearer ")) {
token = token.substring(7); // Remove "Bearer " prefix
try {
String username = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getSubject();
if (username != null) {
// Authentication logic here (populate SecurityContext)
}
} catch (Exception e) {
response.setStatus(403); // Forbidden
}
}
filterChain.doFilter(request, response); // Continue the filter chain
}
}
২.৪.২ SecurityConfig Update
JWT Authentication Filter যোগ করতে WebSecurityConfigurerAdapter ক্লাসে আপডেট করুন:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated() // Only authenticated users can access /api/**
.anyRequest().permitAll()
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); // Add JWT filter
}
}
৩. Rate Limiting এবং Authentication একত্রে ব্যবহার
Spring Cloud Gateway এ API Rate Limiting এবং Authentication একত্রে কনফিগার করতে application.yml ফাইলে দুইটি ফিচারই কনফিগার করা যায়।
spring:
cloud:
gateway:
routes:
- id: api_route
uri: http://example-service
predicates:
- Path=/api/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
redis-rate-limiter.requestedTokens: 1
- name: AddRequestHeader
args:
name: Authorization
value: "Bearer your_token_here"
redis:
host: localhost
port: 6379
সারাংশ:
- Rate Limiting: Spring Cloud Gateway এর মাধ্যমে Redis ব্যবহার করে রিকোয়েস্ট লিমিট সেট করতে পারবেন।
- Authentication: Spring Security এবং JWT ফিল্টার ব্যবহার করে API গেটওয়ের মাধ্যমে Authentication পরিচালনা করতে পারবেন।
- Security Config:
@EnableWebSecurityব্যবহার করে Spring Security কনফিগারেশন সম্পন্ন করতে পারবেন। - Combined Usage: Rate Limiting এবং Authentication একসাথে কনফিগার করার মাধ্যমে নিরাপদ এবং স্কেলেবল API গেটওয়ে নির্মাণ করা যাবে।
এই পদ্ধতিগুলো ব্যবহার করে আপনি Spring Cloud Gateway এর মাধ্যমে Rate Limiting এবং Authentication কনফিগার করতে পারবেন।
API Gateway হল একটি সার্ভিস যা বিভিন্ন মাইক্রোসার্ভিসে একক প্রবেশপথ হিসেবে কাজ করে এবং ক্লায়েন্টের জন্য একাধিক সার্ভিসে রিকোয়েস্ট পাঠানোর কাজে সহায়ক হয়। এটি সাধারণত রাউটিং, লোড ব্যালান্সিং, অথেনটিকেশন, রেট লিমিটিং, এবং অন্যান্য ফিচার পরিচালনা করতে ব্যবহৃত হয়।
Spring Boot অ্যাপ্লিকেশনের মধ্যে API Gateway Integration করার জন্য Spring Cloud Gateway একটি জনপ্রিয় টুল, যা API Gateway হিসেবে কাজ করে।
এখানে Spring Boot Client এর মধ্যে API Gateway Integration এর উদাহরণ দেখানো হলো।
প্রয়োজনীয় ডিপেনডেন্সি
১. Spring Cloud Gateway এর জন্য Maven ডিপেনডেন্সি:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
২. Spring Boot WebFlux (রিঅ্যাকটিভ রিস্পন্স হ্যান্ডলিং জন্য):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
৩. Spring Cloud Config (যদি সেন্ট্রাল কনফিগারেশন দরকার হয়):
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Spring Cloud Gateway Configuration
Spring Cloud Gateway API Gateway হিসেবে কাজ করার জন্য application.yml কনফিগারেশন ফাইল ব্যবহার করা হয়। এই কনফিগারেশনে বিভিন্ন রুট এবং ফিল্টার সেট করা যায়।
1. application.yml কনফিগারেশন:
spring:
cloud:
gateway:
routes:
- id: api-service
uri: http://localhost:8081 # Target service URI
predicates:
- Path=/api/** # Matching API requests
filters:
- AddRequestHeader=X-Request-Foo, Bar # Request header filter
এখানে http://localhost:8081 সার্ভিসে যেকোনো /api/** পাথে রিকোয়েস্ট রুট করা হচ্ছে এবং "X-Request-Foo: Bar" হেডার যুক্ত করা হচ্ছে।
API Gateway এর সাথে Service Integration
ধরা যাক, আমাদের দুইটি মাইক্রোসার্ভিস রয়েছে:
- Service A (এটি API Gateway এর মাধ্যমে ক্লায়েন্ট রিকোয়েস্ট গ্রহণ করবে)
- Service B (এটি API Gateway এর মাধ্যমে রাউট হবে)
এখন API Gateway এর মাধ্যমে রিকোয়েস্ট পাঠানোর জন্য Service A এবং Service B দুইটি স্প্রিং বুট অ্যাপ্লিকেশন তৈরি করা হবে।
Service A (Spring Boot API)
Service A একটি সহজ Spring Boot অ্যাপ্লিকেশন যা /api/data এ রেসপন্স দেয়।
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceAController {
@GetMapping("/api/data")
public String getData() {
return "Data from Service A";
}
}
Service A এই রেসপন্সটি /api/data পাথের জন্য প্রদান করবে।
Service B (Spring Boot API)
Service B অন্য একটি Spring Boot অ্যাপ্লিকেশন যা Service A এর রাউটের মাধ্যমে কল করবে।
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ServiceBController {
private final RestTemplate restTemplate = new RestTemplate();
@GetMapping("/api/data-from-a")
public String getDataFromA() {
String url = "http://localhost:8080/api/data"; // API Gateway route
return restTemplate.getForObject(url, String.class);
}
}
Service B-এর /api/data-from-a রাউটটি Service A থেকে ডেটা নিয়ে আসবে API Gateway এর মাধ্যমে।
Spring Boot Client (Client Application)
এখন ক্লায়েন্ট অ্যাপ্লিকেশন তৈরি করা হবে যা API Gateway এর মাধ্যমে Service A এর /api/data রাউটটিতে কল করবে।
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ClientController {
private final RestTemplate restTemplate = new RestTemplate();
@GetMapping("/get-data")
public String getData() {
// API Gateway থেকে Service A এর ডেটা ফেচ করা
String apiGatewayUrl = "http://localhost:8080/api/data"; // API Gateway URL
return restTemplate.getForObject(apiGatewayUrl, String.class);
}
}
এখানে http://localhost:8080/api/data URL ক্লায়েন্টের মাধ্যমে API Gateway থেকে কল হচ্ছে। API Gateway, সার্ভিস A তে রিকোয়েস্ট পাঠাবে এবং সেখান থেকে রেসপন্স ফিরে আসবে।
API Gateway রাউটিং বিশদ:
এখানে API Gateway এর routes কনফিগারেশন করা হচ্ছে, যাতে নির্দিষ্ট পাথ /api/** এ ক্লায়েন্ট রিকোয়েস্ট এসে একটি নির্দিষ্ট সার্ভিসে পৌঁছাতে পারে।
URI and Filters:
uri: http://localhost:8081: Target সার্ভিসের URL যেখানে API Gateway রিকোয়েস্ট রাউট করবে।predicates: এগুলো হল শর্ত যা যাচাই করে রিকোয়েস্টটি কোথায় রাউট হবে।filters: অতিরিক্ত হেডার বা মডিফিকেশন যা রিকোয়েস্টে করা হয়।
API Gateway Configuration কনফিগারেশন (যদি Service Discovery ব্যবহার করা হয়):
spring:
cloud:
gateway:
routes:
- id: service-a
uri: lb://SERVICE-A # Service Discovery via Eureka
predicates:
- Path=/api/** # Matching API requests
এখানে Service Discovery ব্যবহার করা হচ্ছে। যদি সার্ভিসগুলি Eureka বা অন্য কোনো সার্ভিস ডিসকভারি সিস্টেমে রেজিস্টার থাকে, তবে API Gateway সেই সার্ভিসগুলোর দিকে রিকোয়েস্ট পাঠাবে।
প্রদর্শন (Example Execution)
- Service A:
/api/dataপাথের মাধ্যমে ডেটা সরবরাহ করবে। - Service B:
/api/data-from-aপাথের মাধ্যমে Service A থেকে ডেটা নেবে। - Client:
/get-dataপাথের মাধ্যমে API Gateway এর মাধ্যমে Service A থেকে ডেটা ফেচ করবে।
Client Request Example:
GET http://localhost:8082/get-data
এটি API Gateway এর মাধ্যমে Service A তে কল পাঠাবে এবং Service A থেকে ডেটা ফিরিয়ে আনবে।
Conclusion
Spring Boot Client এর মাধ্যমে API Gateway Integration ব্যবহার করে আপনি একাধিক মাইক্রোসার্ভিসের মধ্যে রিকোয়েস্ট রাউটিং, অথেনটিকেশন, ফিল্টারিং, এবং লোড ব্যালান্সিং পরিচালনা করতে পারেন। Spring Cloud Gateway এর মাধ্যমে এই ফিচারগুলো সহজেই ইমপ্লিমেন্ট করা সম্ভব।
Read more