Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
8.9 kB
6
Indexable
Never
package com.nbt1997.be_genstar.core.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nbt1997.be_genstar.core.component.JwtTokenUtils;
import com.nbt1997.be_genstar.core.component.Localization;
import com.nbt1997.be_genstar.module.admin.constant.AdminConstant;
import com.nbt1997.be_genstar.module.kol.constant.KolConstant;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.CorsConfigurationSource;

@Slf4j
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class SecurityConfig {

	ObjectMapper objectMapper;
	RSAKeyRecord rsaKeyRecord;
	JwtTokenUtils jwtTokenUtils;
	Localization localization;

	@Bean
	public CorsConfigurationSource corsConfigurationSource() {
		CorsConfiguration configuration = new CorsConfiguration();
		configuration.setAllowedOrigins(Arrays.asList("*")); // Allow all origins
		configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); // Allow all methods
		configuration.setAllowedHeaders(Arrays.asList("*")); // Allow all headers
		configuration.setExposedHeaders(Arrays.asList("Authorization")); // Expose Authorization header
		configuration.setAllowCredentials(true);
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", configuration);
		return source;
	}

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		return http
			.cors(cors -> cors.configurationSource(corsConfigurationSource()))
			.csrf(AbstractHttpConfigurer::disable)
			.authorizeHttpRequests(auth -> auth
				.requestMatchers("/**").permitAll()
			)
			.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
			.build();
	}

	@Order(1)
	@Bean
	public SecurityFilterChain swaggerSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
		return httpSecurity
				.securityMatchers((matchers) -> matchers
						.requestMatchers("/v3/api-docs/**",     // Swagger v3 docs endpoint
								"/swagger-ui/**",      // Swagger UI path
								"/swagger-ui.html",    // Swagger UI HTML page
								"/swagger-resources/**",
								"/webjars/**")
				)
				.csrf(AbstractHttpConfigurer::disable)
				.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
				.exceptionHandling(ex -> {
					log.error("[SecurityConfig:swaggerSecurityFilterChain] Exception due to :{}",ex);
				})
				.build();
	}

	@Order(2)
	@Bean
	public SecurityFilterChain publicKolSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
		return httpSecurity
				.securityMatchers((matchers) -> matchers
						.requestMatchers(KolConstant.API.AUTH + KolConstant.API.LOGIN + "/**",
								KolConstant.API.AUTH + KolConstant.API.REGISTER + "/**")
				)
				.cors(AbstractHttpConfigurer::disable)
				.csrf(AbstractHttpConfigurer::disable)
				.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
				.exceptionHandling(ex -> {
					log.error("[SecurityConfig:publicKolSecurityFilterChain] Exception due to :{}",ex);
				})
				.build();
	}

	@Order(3)
	@Bean
	public SecurityFilterChain publicAdminSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
		return httpSecurity
				.securityMatchers((matchers) -> matchers
						.requestMatchers(AdminConstant.API.LOGIN + AdminConstant.API.LOGIN + "/**")
				)
				.cors(AbstractHttpConfigurer::disable)
				.csrf(AbstractHttpConfigurer::disable)
				.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
				.exceptionHandling(ex -> {
					log.error("[SecurityConfig:publicAdminSecurityFilterChain] Exception due to :{}",ex);
				})
				.build();
	}

//	@Order(1)
//	@Bean
//	public SecurityFilterChain signInSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
//		return httpSecurity
//				.securityMatcher(new AntPathRequestMatcher(AUTH.PREFIX + AUTH.SIGN_IN + "/**"))
//				.csrf(AbstractHttpConfigurer::disable)
//				.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
//				.exceptionHandling(ex -> {
//					log.error("[SecurityConfig:signInSecurityFilterChain] Exception due to :{}",ex);
//				})
//				.build();
//	}

//	@Order(2)
//	@Bean
//	public SecurityFilterChain apiSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
//		return httpSecurity
//				.securityMatcher(new AntPathRequestMatcher("/api/**"))
//				.csrf(AbstractHttpConfigurer::disable)
//				.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
//				.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()))
//				.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
//				.addFilterBefore(new JwtAccessTokenFilter(objectMapper, rsaKeyRecord, jwtTokenUtils, localizationUtils), UsernamePasswordAuthenticationFilter.class)
//				.exceptionHandling(ex -> {
//					log.error("[SecurityConfig:apiSecurityFilterChain] Exception due to :{}",ex);
//					ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint());
//					ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler());
//				})
//				.httpBasic(withDefaults())
//				.build();
//	}
//
//	@Order(3)
//	@Bean
//	public SecurityFilterChain refreshTokenSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
//		return httpSecurity
//				.securityMatcher(new AntPathRequestMatcher(AUTH.PREFIX + AUTH.REFRESH_TOKEN + "/**"))
//				.csrf(AbstractHttpConfigurer::disable)
//				.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
//				.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()))
//				.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
//				.addFilterBefore(new JwtRefreshTokenFilter(rsaKeyRecord, jwtTokenUtils, refreshTokenRepository), UsernamePasswordAuthenticationFilter.class)
//				.exceptionHandling(ex -> {
//					log.error("[SecurityConfig:refreshTokenSecurityFilterChain] Exception due to :{}",ex);
//					ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint());
//					ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler());
//				})
//				.httpBasic(withDefaults())
//				.build();
//	}

	@Bean
	PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	JwtDecoder jwtDecoder(){
		return NimbusJwtDecoder.withPublicKey(rsaKeyRecord.rsaPublicKey()).build();
	}

	@Bean
	JwtEncoder jwtEncoder(){
		JWK jwk = new RSAKey.Builder(rsaKeyRecord.rsaPublicKey()).privateKey(rsaKeyRecord.rsaPrivateKey()).build();
		JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
		return new NimbusJwtEncoder(jwkSource);
	}

	@Bean
	JwtAuthenticationConverter jwtAuthenticationConverter() {
		JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
		jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");

		JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
		jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);

		return jwtAuthenticationConverter;
	}
}
Leave a Comment