الأمان
أمان الخدمات المصغّرة باستخدام Spring Security وOAuth2
10-15 دقيقة
أمان الخدمات المصغّرة باستخدام Spring Security وOAuth2
يُعدّ الأمان جانبًا بالغ الأهمية في معماريات الخدمات المصغّرة. يتيح كل من Spring Security وOAuth2 إرساء مصادقة وتفويض قويين.
1. إعداد خادم التفويض
1.1 إنشاء مشروع Auth Server
curl https://start.spring.io/starter.tgz \
-d dependencies=oauth2-resource-server,oauth2-authorization-server \
-d groupId=com.example \
-d artifactId=auth-server \
-d name=auth-server \
-d description=OAuth2%20Authorization%20Server \
-d packageName=com.example.auth \
-d packaging=jar \
-d javaVersion=17 \
-d type=maven-project \
| tar -xzvf -
1.2 إعداد الخادم
# application.yml
server:
port: 9000
spring:
application:
name: auth-server
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:9000
jwk-set-uri: http://localhost:9000/.well-known/jwks.json
1.3 إعداد الأمان
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf().disable()
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/oauth2/**", "/login/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwtAuthenticationConverter(jwtAuthenticationConverter())
)
)
.build();
}
@Bean
public Converter<Jwt, AbstractAuthenticationToken> jwtAuthenticationConverter() {
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
jwtConverter.setJwtGrantedAuthoritiesConverter(jwt -> {
List<String> roles = jwt.getClaimAsStringList("roles");
return roles.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toList());
});
return jwtConverter;
}
}
التعليقات
التعليقات مدعومة عبر GitHub Discussions
سجّل الدخول باستخدام GitHub للمشاركة في النقاش