Spring Security 7.x + JDK 25 加密升级
⚔️ 技文侠出品必属精品开篇安全是最后的底线JDK 25 带来了新一代加密 APISpring Security 7.x 全面拥抱响应式安全。本文将深入讲解如何构建面向未来的安全架构。一、JDK 25 加密新特性1.1 新一代加密 API// JDK 25 新增KeyEncapsulation密钥封装KeyEncapsulationkemKeyEncapsulation.getInstance(KEMs/X25519);KeyPairkpkem.generateKeyPair();// 密钥封装SecretKeysecretKeykem.encapsulate(kp.getPublic());byte[]ciphertextkem.getCiphertext();// 解封装SecretKeyreceivedKeykem.decapsulate(kp.getPrivate(),ciphertext);1.2 增强的密码学随机数// JDK 21SecureRandom.getInstanceStrong() 改进SecureRandomrandomSecureRandom.getInstanceStrong();// 生成密码学安全的随机数byte[]keynewbyte[32];random.nextBytes(key);1.3 简化加密操作// 新一代加密 APICipher 简化// 传统方式CiphercipherCipher.getInstance(AES/GCM/NoPadding);cipher.init(Cipher.ENCRYPT_MODE,key);byte[]ciphertextcipher.doFinal(plaintext);// JDK 25 简化方式SealedObject 增强SealedObjectsealednewSealedObject(plaintext,cipher);Objectplaintext2sealed.getObject(key);二、Spring Security 7.x 核心配置2.1 基本配置ConfigurationEnableWebSecurityEnableMethodSecuritypublicclassSecurityConfig{BeanpublicSecurityFilterChainfilterChain(HttpSecurityhttp)throwsException{http.authorizeHttpRequests(auth-auth.requestMatchers(/api/public/**,/actuator/health).permitAll().requestMatchers(/api/admin/**).hasRole(ADMIN).requestMatchers(/api/user/**).authenticated().anyRequest().authenticated()).csrf(csrf-csrf.ignoringRequestMatchers(/api/**)).sessionManagement(session-session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).cors(cors-cors.configurationSource(corsConfigurationSource()));returnhttp.build();}}2.2 JWT 认证ComponentpublicclassJwtTokenProvider{Value(${jwt.secret})privateStringsecretKey;publicStringgenerateToken(UserDetailsuser){DatenownewDate();DateexpiryDatenewDate(now.getTime()86400000);returnJwts.builder().subject(user.getUsername()).claim(roles,user.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList()).issuedAt(now).expiration(expiryDate).signWith(Keys.hmacShaKeyFor(secretKey.getBytes()),Jwts.SIG.HS256).compact();}publicbooleanvalidateToken(Stringtoken){try{Jwts.parser().verifyWith(Keys.hmacShaKeyFor(secretKey.getBytes())).build().parseSignedClaims(token);returntrue;}catch(JwtException|IllegalArgumentExceptione){returnfalse;}}}三、响应式安全3.1 WebFlux 安全配置ConfigurationEnableWebFluxSecuritypublicclassReactiveSecurityConfig{BeanpublicSecurityWebFilterChainsecurityWebFilterChain(ServerHttpSecurityhttp){returnhttp.authorizeExchange(exchange-exchange.pathMatchers(/api/public/**).permitAll().pathMatchers(/api/admin/**).hasRole(ADMIN).anyExchange().authenticated()).csrf(ServerCsrfToken::disable).oauth2ResourceServer(oauth2-oauth2.jwt(Customizer.withDefaults())).build();}}3.2 响应式认证管理器ComponentpublicclassReactiveAuthenticationManagerimplementsReactiveAuthenticationManager{AutowiredprivateJwtTokenProviderjwtTokenProvider;OverridepublicMonoAuthenticationauthenticate(Authenticationauthentication){Stringtokenauthentication.getCredentials().toString();if(!jwtTokenProvider.validateToken(token)){returnMono.error(newBadCredentialsException(Invalid token));}StringusernamejwtTokenProvider.getUsername(token);returnMono.just(newUsernamePasswordAuthenticationToken(username,null,List.of(newSimpleGrantedAuthority(ROLE_USER))));}}四、密码加密升级4.1 BCrypt 增强ConfigurationpublicclassPasswordEncoderConfig{BeanpublicPasswordEncoderpasswordEncoder(){// BCrypt 12 轮强度默认returnnewBCryptPasswordEncoder(12);}}4.2 Argon2 密码哈希dependencygroupIdde.mkammerer/groupIdartifactIdargon2-jvm/artifactIdversion2.8/version/dependencyConfigurationpublicclassArgon2Config{BeanpublicPasswordEncoderpasswordEncoder(){returnArgon2PasswordEncoder.defaultsForSpringSecurity_v5_8();}}五、OAuth 2.0 最佳实践5.1 授权服务器配置spring:security:oauth2:authorizationserver:issuer:http://localhost:9000authorization:settings:settings:oauth2:token:endpoint:access-token-request-parameter-name:authorization_codetoken-revocation:endpoint:access-token-request-parameter-name:access_token5.2 资源服务器ConfigurationEnableWebSecurityEnableMethodSecuritypublicclassResourceServerConfig{BeanpublicSecurityFilterChainsecurityFilterChain(HttpSecurityhttp)throwsException{http.oauth2ResourceServer(oauth2-oauth2.jwt(Customizer.withDefaults())).authorizeHttpRequests(auth-auth.requestMatchers(/api/public/**).permitAll().anyRequest().authenticated());returnhttp.build();}}六、敏感数据加密6.1 配置加密spring:datasource:password:ENC(ciphertext)# 使用 jasypt 加密jasypt:encryptor:password:${JASYPT_PASSWORD}6.2 字段级加密ComponentpublicclassEncryptionService{AutowiredprivateAESEncryptionServiceaesService;// 加密方法publicStringencrypt(Stringplaintext){returnaesService.encrypt(plaintext);}// 解密方法publicStringdecrypt(Stringciphertext){returnaesService.decrypt(ciphertext);}}// 在 Entity 中使用EntitypublicclassUser{Convert(converterEncryptionConverter.class)privateStringphone;Convert(converterEncryptionConverter.class)privateStringidCard;}七、安全监控7.1 登录失败监控ServicepublicclassLoginAttemptService{AutowiredprivateRedisTemplateString,IntegerredisTemplate;privatestaticfinalintMAX_ATTEMPTS5;publicvoidrecordFailedLogin(Stringusername){Stringkeylogin:fail:username;IntegerattemptsredisTemplate.opsForValue().increment(key);if(attempts!nullattemptsMAX_ATTEMPTS){// 锁定账户redisTemplate.opsForValue().set(login:lock:username,1,Duration.ofMinutes(30));}}publicvoidclearLoginAttempts(Stringusername){redisTemplate.delete(login:fail:username);}publicbooleanisLocked(Stringusername){returnBoolean.TRUE.equals(redisTemplate.hasKey(login:lock:username));}}7.2 安全审计日志ComponentpublicclassSecurityAuditLogger{AutowiredprivateAuditServiceauditService;publicvoidlogLoginSuccess(Stringusername,Stringip){auditService.audit(LOGIN_SUCCESS,username,ip,User logged in);}publicvoidlogLoginFailure(Stringusername,Stringip,Stringreason){auditService.audit(LOGIN_FAILURE,username,ip,reason);}publicvoidlogAccessDenied(Stringusername,Stringresource){auditService.audit(ACCESS_DENIED,username,null,Attempted to access: resource);}}八、 HTTPS 配置8.1 自签名证书开发环境# 生成自签名证书keytool-genkeypair\-aliasecommerce\-keyalgRSA\-keysize2048\-storetypePKCS12\-keystorekeystore.p12\-validity3650\-storepasschangeit\-keypasschangeit\-dnameCNlocalhost, OUDev, ODev, LBJ, STBJ, CCN8.2 HTTPS 配置server:ssl:key-store:classpath:keystore.p12key-store-password:changeitkey-store-type:PKCS12key-alias:ecommerceenabled:truehttp2:enabled:true九、安全检查清单使用 HTTPS 强制密码加密存储BCrypt 12轮JWT 合理设置过期时间实现登录失败锁定敏感数据字段级加密开启 CSRF 防护API 场景可禁用配置 CORS 策略记录安全审计日志定期更新依赖版本⚔️技文侠曰安全不是事后补救而是架构设计的第一天条。JDK 25 的新加密 API Spring Security 7.x让安全代码更优雅、更安全。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2448864.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!