安全与效率优化,引入Redis,包名修改
This commit is contained in:
+63
@@ -0,0 +1,63 @@
|
||||
package com.linkerbot.vibemake.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.vibemake.common.*;
|
||||
import com.linkerbot.vibemake.service.UserService;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.web.context.SecurityContextRepository;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BearerTokenFilter extends OncePerRequestFilter {
|
||||
private final TokenService tokens;
|
||||
private final UserService users;
|
||||
private final ObjectMapper json;
|
||||
private final SecurityContextRepository contextRepository;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header != null && header.startsWith("Bearer ")) {
|
||||
try {
|
||||
TokenService.Session session = tokens.session(header.substring(7));
|
||||
Long id = session == null ? null : session.userId();
|
||||
if (id == null) throw new BusinessException(401, "UNAUTHORIZED", "登录已失效,请重新登录");
|
||||
com.linkerbot.vibemake.bean.entity.User user = users.require(id);
|
||||
if (!"USER".equals(user.getRole()) || user.getSessionVersion() != session.version())
|
||||
throw new BusinessException(401, "UNAUTHORIZED", "登录已失效,请重新登录");
|
||||
UsernamePasswordAuthenticationToken auth =
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
new CurrentUser.Principal(id),
|
||||
null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(auth);
|
||||
SecurityContextHolder.setContext(context);
|
||||
contextRepository.saveContext(context, request, response);
|
||||
} catch (BusinessException error) {
|
||||
response.setStatus(error.status());
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
json.writeValue(response.getOutputStream(), ApiResponse.failure(error));
|
||||
return;
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.linkerbot.vibemake.security;
|
||||
|
||||
import com.linkerbot.vibemake.bean.Contracts.CaptchaView;
|
||||
import com.linkerbot.vibemake.common.*;
|
||||
import com.linkerbot.vibemake.common.state.TransientStateStore;
|
||||
import com.linkerbot.vibemake.service.config.VibemakeProperties;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
@Service
|
||||
public class CaptchaService {
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final TransientStateStore challenges;
|
||||
private final VibemakeProperties config;
|
||||
|
||||
public CaptchaService(VibemakeProperties config, TransientStateStore challenges) {
|
||||
this.config = config;
|
||||
this.challenges = challenges;
|
||||
}
|
||||
|
||||
protected String generateAnswer() {
|
||||
String alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < 5; i++)
|
||||
result.append(alphabet.charAt(random.nextInt(alphabet.length())));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public CaptchaView issue() {
|
||||
String answer = generateAnswer();
|
||||
BufferedImage image = new BufferedImage(180, 60, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D graphics = image.createGraphics();
|
||||
try {
|
||||
graphics.setColor(new Color(245, 247, 250));
|
||||
graphics.fillRect(0, 0, 180, 60);
|
||||
for (int i = 0; i < 10; i++) {
|
||||
graphics.setColor(
|
||||
new Color(random.nextInt(160), random.nextInt(160), random.nextInt(160)));
|
||||
graphics.drawLine(
|
||||
random.nextInt(180),
|
||||
random.nextInt(60),
|
||||
random.nextInt(180),
|
||||
random.nextInt(60));
|
||||
}
|
||||
graphics.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 30));
|
||||
for (int i = 0; i < answer.length(); i++) {
|
||||
graphics.setColor(
|
||||
new Color(random.nextInt(100), random.nextInt(100), random.nextInt(100)));
|
||||
graphics.drawString(
|
||||
String.valueOf(answer.charAt(i)), 15 + i * 30, 38 + random.nextInt(8));
|
||||
}
|
||||
} finally {
|
||||
graphics.dispose();
|
||||
}
|
||||
try (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
|
||||
ImageIO.write(image, "png", bytes);
|
||||
String code = Codes.next();
|
||||
if (!challenges.putIfAbsent(
|
||||
"captcha:" + code, SecurityHashes.sha256(answer), config.getCaptchaTtl()))
|
||||
throw new BusinessException(503, "CAPTCHA_ERROR", "验证码分配失败,请重试");
|
||||
return new CaptchaView(
|
||||
code,
|
||||
"data:image/png;base64,"
|
||||
+ Base64.getEncoder().encodeToString(bytes.toByteArray()),
|
||||
config.getCaptchaTtl().toSeconds());
|
||||
} catch (IOException error) {
|
||||
throw new BusinessException(500, "CAPTCHA_ERROR", "验证码生成失败");
|
||||
}
|
||||
}
|
||||
|
||||
public void verify(String code, String answer) {
|
||||
if (code == null || !code.matches("[a-f0-9]{32}"))
|
||||
throw new BusinessException(400, "CAPTCHA_INVALID", "图片验证码错误、已使用或已过期");
|
||||
String expected = challenges.consume("captcha:" + code);
|
||||
String actual = answer == null ? "" : answer.trim().toUpperCase(Locale.ROOT);
|
||||
if (expected == null
|
||||
|| !MessageDigest.isEqual(
|
||||
expected.getBytes(StandardCharsets.UTF_8),
|
||||
SecurityHashes.sha256(actual).getBytes(StandardCharsets.UTF_8)))
|
||||
throw new BusinessException(400, "CAPTCHA_INVALID", "图片验证码错误、已使用或已过期");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.linkerbot.vibemake.security;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "vibemake.cors")
|
||||
public class CorsProperties {
|
||||
private List<String> allowedOrigins = List.of();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.linkerbot.vibemake.security;
|
||||
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public final class CurrentUser {
|
||||
private CurrentUser() {}
|
||||
|
||||
public record Principal(long userId) {}
|
||||
|
||||
public static Long optional() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
return auth != null && auth.getPrincipal() instanceof Principal principal
|
||||
? principal.userId()
|
||||
: null;
|
||||
}
|
||||
|
||||
public static long required() {
|
||||
Long id = optional();
|
||||
if (id == null) throw new BusinessException(401, "UNAUTHORIZED", "请先登录");
|
||||
return id;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package com.linkerbot.vibemake.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.vibemake.common.*;
|
||||
import com.linkerbot.vibemake.service.state.HttpSafetyFilter;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
|
||||
import org.springframework.security.web.context.SecurityContextRepository;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfiguration {
|
||||
private static final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<HttpSafetyFilter> disableSafetyServletRegistration(
|
||||
HttpSafetyFilter filter) {
|
||||
FilterRegistrationBean<HttpSafetyFilter> registration =
|
||||
new FilterRegistrationBean<>(filter);
|
||||
registration.setEnabled(false);
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public UrlBasedCorsConfigurationSource corsConfigurationSource(CorsProperties properties) {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOrigins(properties.getAllowedOrigins());
|
||||
configuration.setAllowedMethods(
|
||||
List.of("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(
|
||||
List.of(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT));
|
||||
configuration.setExposedHeaders(
|
||||
List.of("X-Request-Id", HttpHeaders.CONTENT_DISPOSITION, "Retry-After"));
|
||||
configuration.setAllowCredentials(false);
|
||||
configuration.setMaxAge(3600L);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/api/**", configuration);
|
||||
log.info("API 跨域配置已加载 path=/api/** allowedOrigins={}", properties.getAllowedOrigins());
|
||||
return source;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityContextRepository requestSecurityContextRepository() {
|
||||
// 仅在本次请求及其异步分派内保留身份,不创建 HttpSession。
|
||||
return new RequestAttributeSecurityContextRepository();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<BearerTokenFilter> disableServletRegistration(
|
||||
BearerTokenFilter filter) {
|
||||
FilterRegistrationBean<BearerTokenFilter> registration =
|
||||
new FilterRegistrationBean<>(filter);
|
||||
registration.setEnabled(false);
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(
|
||||
HttpSecurity http,
|
||||
BearerTokenFilter tokenFilter,
|
||||
ObjectMapper json,
|
||||
SecurityContextRepository contextRepository,
|
||||
UrlBasedCorsConfigurationSource corsConfigurationSource,
|
||||
HttpSafetyFilter safety)
|
||||
throws Exception {
|
||||
// 在 Token 鉴权前处理预检,并让鉴权失败响应同样携带跨域头。
|
||||
http.cors(cors -> cors.configurationSource(corsConfigurationSource))
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(
|
||||
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.securityContext(context -> context.securityContextRepository(contextRepository))
|
||||
.formLogin(form -> form.disable())
|
||||
.httpBasic(basic -> basic.disable())
|
||||
.logout(logout -> logout.disable())
|
||||
.authorizeHttpRequests(
|
||||
auth ->
|
||||
auth.requestMatchers(
|
||||
"/api/auth/captcha",
|
||||
"/api/auth/login",
|
||||
"/v3/api-docs/**",
|
||||
"/swagger-ui/**",
|
||||
"/swagger-ui.html",
|
||||
"/error")
|
||||
.permitAll()
|
||||
.requestMatchers(
|
||||
HttpMethod.GET,
|
||||
"/api/community/**",
|
||||
"/api/project-types")
|
||||
.permitAll()
|
||||
.requestMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated())
|
||||
.exceptionHandling(
|
||||
errors ->
|
||||
errors.authenticationEntryPoint(
|
||||
(request, response, error) -> {
|
||||
response.setStatus(401);
|
||||
response.setContentType(
|
||||
"application/json;charset=UTF-8");
|
||||
json.writeValue(
|
||||
response.getOutputStream(),
|
||||
ApiResponse.failure(
|
||||
new BusinessException(
|
||||
401,
|
||||
"UNAUTHORIZED",
|
||||
"请先登录")));
|
||||
})
|
||||
.accessDeniedHandler(
|
||||
(request, response, error) -> {
|
||||
response.setStatus(403);
|
||||
response.setContentType(
|
||||
"application/json;charset=UTF-8");
|
||||
json.writeValue(
|
||||
response.getOutputStream(),
|
||||
ApiResponse.failure(
|
||||
new BusinessException(
|
||||
403,
|
||||
"FORBIDDEN",
|
||||
"无权访问")));
|
||||
}))
|
||||
.addFilterAfter(safety, org.springframework.web.filter.CorsFilter.class)
|
||||
.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.linkerbot.vibemake.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
import com.linkerbot.vibemake.common.SecurityHashes;
|
||||
import com.linkerbot.vibemake.common.state.TransientStateStore;
|
||||
import com.linkerbot.vibemake.service.config.VibemakeProperties;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
@Service
|
||||
public class TokenService {
|
||||
private final TransientStateStore sessions;
|
||||
private final VibemakeProperties config;
|
||||
private final ObjectMapper json;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public TokenService(
|
||||
VibemakeProperties config, TransientStateStore sessions, ObjectMapper json) {
|
||||
this.config = config;
|
||||
this.sessions = sessions;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
public record Session(long userId, long version) {}
|
||||
|
||||
public String issue(long userId) {
|
||||
return issue(userId, 0L);
|
||||
}
|
||||
|
||||
public String issue(long userId, long version) {
|
||||
try {
|
||||
String value = json.writeValueAsString(new Session(userId, version));
|
||||
for (int attempt = 0; attempt < 3; attempt++) {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
if (sessions.putIfAbsent(key(token), value, config.getTokenTtl())) return token;
|
||||
}
|
||||
throw new IllegalStateException("会话编码分配失败");
|
||||
} catch (java.io.IOException error) {
|
||||
throw new BusinessException(503, "SESSION_UNAVAILABLE", "会话服务暂不可用");
|
||||
}
|
||||
}
|
||||
|
||||
public Long resolve(String token) {
|
||||
Session session = session(token);
|
||||
return session == null ? null : session.userId();
|
||||
}
|
||||
|
||||
public Session session(String token) {
|
||||
if (token == null || !token.matches("[A-Za-z0-9_-]{43}")) return null;
|
||||
String value = sessions.get(key(token));
|
||||
if (value == null) return null;
|
||||
try {
|
||||
Session session = json.readValue(value, Session.class);
|
||||
if (session == null || session.userId() <= 0 || session.version() < 0)
|
||||
throw new IllegalArgumentException("会话数据异常");
|
||||
return session;
|
||||
} catch (java.io.IOException | IllegalArgumentException error) {
|
||||
throw new BusinessException(503, "SESSION_UNAVAILABLE", "会话数据异常,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
public void revoke(String token) {
|
||||
if (token != null) sessions.remove(key(token));
|
||||
}
|
||||
|
||||
private String key(String token) {
|
||||
return "session:" + SecurityHashes.sha256(token);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user