5.22
一、JWT 认证与授权
基于 Spring Security 实现 JWT 认证流程:
java
// JWT过滤器
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && jwtProvider.validateToken(jwt)) {
String username = jwtProvider.getUsernameFromJwt(jwt);
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, null, Collections.emptyList()));
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;
}
}
// 安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
二、数据加密与脱敏
实现敏感数据的加密存储和展示:
java
// 数据加密工具类
public class EncryptionUtil {
private static final String ALGORITHM = "AES/GCM/NoPadding";
private static final int TAG_LENGTH_BIT = 128;
private static final int IV_LENGTH_BYTE = 12;
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, new byte[IV_LENGTH_BYTE]);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec);
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, new byte[IV_LENGTH_BYTE]);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
byte[] decrypted = cipher.doFinal(encryptedBytes);
return new String(decrypted, StandardCharsets.UTF_8);
}
}
// 数据脱敏注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SensitiveData {
SensitiveType type() default SensitiveType.DEFAULT;
}
// 脱敏处理器
public class SensitiveDataProcessor {
public static Object process(Object obj) throws IllegalAccessException {
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(SensitiveData.class)) {
field.setAccessible(true);
Object value = field.get(obj);
if (value instanceof String) {
SensitiveData annotation = field.getAnnotation(SensitiveData.class);
String maskedValue = mask((String) value, annotation.type());
field.set(obj, maskedValue);
}
}
}
return obj;
}
private static String mask(String value, SensitiveType type) {
// 根据不同类型实现脱敏逻辑
switch (type) {
case PHONE:
return value.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
case ID_CARD:
return value.replaceAll("(\\d{6})\\d{8}(\\d{4})", "$1********$2");
default:
return value.replaceAll("(\\S)\\S*(\\S)", "$1***$2");
}
}
}

浙公网安备 33010602011771号