Temel Form Tabanlı Kimlik Doğrulama
Bu senaryo, kullanıcıların kullanıcı adı ve şifre ile oturum açmasını sağlar.
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll();}}
Rol Tabanlı Yetkilendirme
Farklı rollere sahip kullanıcılar için farklı erişim hakları tanımlar.
@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasAnyRole("USER", "ADMIN").anyRequest().authenticated().and().formLogin();}
JWT (JSON Web Token) Kimlik Doğrulama
Stateless kimlik doğrulama için JWT kullanımı.
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JwtTokenProvider jwtTokenProvider;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().anyRequest().authenticated().and().apply(new JwtConfigurer(jwtTokenProvider));}}
OAuth2 ile Sosyal Medya Girişi
Google, Facebook gibi sosyal medya hesaplarıyla giriş yapma imkanı sunar.
@Configuration@EnableWebSecuritypublic class OAuth2LoginConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().oauth2Login();}}
Remember Me Fonksiyonu
Kullanıcının oturumunu hatırlama özelliği ekler.
@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400);}
CSRF (Cross-Site Request Forgery) Koruması
CSRF saldırılarına karşı koruma sağlar.
@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());}
CORS (Cross-Origin Resource Sharing) Yapılandırması
Farklı kaynaklardan gelen isteklere izin verir.
@Beanpublic CorsConfigurationSource corsConfigurationSource() {CorsConfiguration configuration = new CorsConfiguration();configuration.setAllowedOrigins(Arrays.asList("https://example.com"));configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", configuration);return source;}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.cors();}
Özel Kimlik Doğrulama Sağlayıcısı
Özel bir kimlik doğrulama mantığı uygulamak için.
@Configurationpublic class CustomAuthenticationProvider implements AuthenticationProvider {@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String username = authentication.getName();String password = authentication.getCredentials().toString();// Özel kimlik doğrulama mantığı buradareturn new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());}@Overridepublic boolean supports(Class<?> authentication) {return authentication.equals(UsernamePasswordAuthenticationToken.class);}}@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider(new CustomAuthenticationProvider());}
Method Düzeyinde Güvenlik
Belirli metotlara erişimi kısıtlar.
@Configuration@EnableGlobalMethodSecurity(prePostEnabled = true)public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {}@Servicepublic class UserService {@PreAuthorize("hasRole('ADMIN')")public void deleteUser(Long userId) {// Kullanıcı silme işlemi}}
Şifreleme ve Şifre Karması
Kullanıcı şifrelerini güvenli bir şekilde saklamak için.
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());}}
Session Fixation Koruması
Oturum sabitleme saldırılarına karşı koruma sağlar.
@Overrideprotected void configure(HttpSecurity http) throws Exception {http.sessionManagement().sessionFixation().migrateSession().and().authorizeRequests().anyRequest().authenticated().and().formLogin();}
Brute Force Saldırı Koruması
Başarısız giriş denemelerini sınırlandırarak brute force saldırılarını engeller.
@Beanpublic DaoAuthenticationProvider authenticationProvider() {DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();authProvider.setUserDetailsService(userDetailsService);authProvider.setPasswordEncoder(passwordEncoder());authProvider.setPreAuthenticationChecks(new AccountStatusUserDetailsChecker() {@Overridepublic void check(UserDetails user) {super.check(user);if (user instanceof LockableUser && ((LockableUser) user).isTemporarilyLocked()) {throw new LockedException("Account is temporarily locked");}}});return authProvider;}// LockableUser sınıfı ve ilgili servis uygulamaları gereklidir
SSL/TLS Zorunluluğu
HTTPS kullanımını zorunlu kılar.
@Overrideprotected void configure(HttpSecurity http) throws Exception {http.requiresChannel().anyRequest().requiresSecure().and().authorizeRequests().anyRequest().authenticated().and().formLogin();}
IP Tabanlı Erişim Kontrolü
Belirli IP adreslerine erişimi kısıtlar veya izin verir.
@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasIpAddress("192.168.1.0/24").anyRequest().authenticated().and().formLogin();}
İki Faktörlü Kimlik Doğrulama (2FA)
Ek bir güvenlik katmanı olarak iki faktörlü kimlik doğrulama ekler.
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate TwoFactorAuthenticationProvider twoFactorAuthenticationProvider;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().addFilterBefore(new TwoFactorAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider(twoFactorAuthenticationProvider);}}// TwoFactorAuthenticationProvider ve TwoFactorAuthenticationFilter sınıflarının uygulanması gerekir
OAuth2 Resource Server
Bir OAuth2 kaynak sunucusu olarak davranır.
@Configuration@EnableResourceServerpublic class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/api/**").authenticated().and().oauth2ResourceServer().jwt();}}
Şüpheli Aktivite Loglama
Güvenlik olaylarını loglamak için özel bir filtre ekler.
public class SecurityLoggingFilter extends GenericFilterBean {private static final Logger logger = LoggerFactory.getLogger(SecurityLoggingFilter.class);@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {HttpServletRequest httpRequest = (HttpServletRequest) request;logger.info("Request from IP: " + httpRequest.getRemoteAddr() +" to URL: " + httpRequest.getRequestURL());chain.doFilter(request, response);}}@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.addFilterBefore(new SecurityLoggingFilter(), UsernamePasswordAuthenticationFilter.class)// ... diğer konfigürasyonlar}}
Özel Yetkilendirme Kuralları
Karmaşık yetkilendirme senaryoları için özel bir AccessDecisionVoter uygulaması.
public class CustomAccessDecisionVoter implements AccessDecisionVoter<Object> {@Overridepublic boolean supports(ConfigAttribute attribute) {return true;}@Overridepublic boolean supports(Class<?> clazz) {return true;}@Overridepublic int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {// Özel yetkilendirme mantığı buradareturn ACCESS_GRANTED;}}@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager());}@Beanpublic AccessDecisionManager accessDecisionManager() {List<AccessDecisionVoter<?>> decisionVoters = Arrays.asList(new WebExpressionVoter(),new RoleVoter(),new AuthenticatedVoter(),new CustomAccessDecisionVoter());return new UnanimousBased(decisionVoters);}}
Asenkron Metot Güvenliği
Asenkron metotlar için güvenlik kuralları uygular.
@Configuration@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)@EnableAsyncpublic class MethodSecurityConfig extends AsyncConfigurerSupport {@Overridepublic Executor getAsyncExecutor() {return new DelegatingSecurityContextExecutorService(Executors.newFixedThreadPool(5));}}@Servicepublic class AsyncService {@Async@PreAuthorize("hasRole('ADMIN')")public CompletableFuture<String> performAsyncTask() {// Asenkron işlemreturn CompletableFuture.completedFuture("Task completed");}}
Özel Login Sayfası
Özelleştirilmiş bir login sayfası kullanır.
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/custom-login").loginProcessingUrl("/perform_login").defaultSuccessUrl("/homepage", true).failureUrl("/custom-login?error=true").permitAll().and().logout().logoutSuccessUrl("/custom-login?logout=true").permitAll();}}
