社区初始化
This commit is contained in:
+54
@@ -0,0 +1,54 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.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.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;
|
||||
|
||||
@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 {
|
||||
Long id = tokens.resolve(header.substring(7));
|
||||
if (id == null) throw new BusinessException(401, "UNAUTHORIZED", "登录已失效,请重新登录");
|
||||
users.require(id);
|
||||
UsernamePasswordAuthenticationToken auth =
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
new CurrentUser.Principal(id),
|
||||
null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
} 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,95 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.linkerbot.community.bean.Contracts.CaptchaView;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
|
||||
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 Cache<String, String> challenges;
|
||||
private final CommunityProperties config;
|
||||
|
||||
public CaptchaService(CommunityProperties config) {
|
||||
this.config = config;
|
||||
this.challenges =
|
||||
Caffeine.newBuilder()
|
||||
.maximumSize(10000)
|
||||
.expireAfterWrite(config.getCaptchaTtl())
|
||||
.build();
|
||||
}
|
||||
|
||||
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();
|
||||
challenges.put(code, answer);
|
||||
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) {
|
||||
String expected = challenges.asMap().remove(code);
|
||||
String actual = answer == null ? "" : answer.trim().toUpperCase(Locale.ROOT);
|
||||
if (expected == null
|
||||
|| !MessageDigest.isEqual(
|
||||
expected.getBytes(StandardCharsets.UTF_8),
|
||||
actual.getBytes(StandardCharsets.UTF_8)))
|
||||
throw new BusinessException(400, "CAPTCHA_INVALID", "图片验证码错误、已使用或已过期");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.linkerbot.community.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;
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.community.common.*;
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.*;
|
||||
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;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfiguration {
|
||||
@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) throws Exception {
|
||||
http.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(
|
||||
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.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",
|
||||
"无权访问")));
|
||||
}))
|
||||
.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
@Service
|
||||
public class TokenService {
|
||||
private final Cache<String, Long> sessions;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public TokenService(CommunityProperties config) {
|
||||
sessions =
|
||||
Caffeine.newBuilder()
|
||||
.maximumSize(10000)
|
||||
.expireAfterWrite(config.getTokenTtl())
|
||||
.build();
|
||||
}
|
||||
|
||||
public String issue(long userId) {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
sessions.put(token, userId);
|
||||
return token;
|
||||
}
|
||||
|
||||
public Long resolve(String token) {
|
||||
return sessions.getIfPresent(token);
|
||||
}
|
||||
|
||||
public void revoke(String token) {
|
||||
if (token != null) sessions.invalidate(token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
class SessionTest {
|
||||
@Test
|
||||
void expiredCaptchaAndTokenCannotBeUsed() throws Exception {
|
||||
CommunityProperties properties = new CommunityProperties();
|
||||
properties.setCaptchaTtl(Duration.ofMillis(1));
|
||||
properties.setTokenTtl(Duration.ofMillis(1));
|
||||
CaptchaService captcha =
|
||||
new CaptchaService(properties) {
|
||||
@Override
|
||||
protected String generateAnswer() {
|
||||
return "ABCDE";
|
||||
}
|
||||
};
|
||||
String code = captcha.issue().captchaCode();
|
||||
TokenService tokens = new TokenService(properties);
|
||||
String token = tokens.issue(1L);
|
||||
Thread.sleep(20);
|
||||
assertThatThrownBy(() -> captcha.verify(code, "ABCDE"))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
assertThat(tokens.resolve(token)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokensAreRandomAndRevocable() {
|
||||
TokenService tokens = new TokenService(new CommunityProperties());
|
||||
String a = tokens.issue(1L);
|
||||
String b = tokens.issue(1L);
|
||||
assertThat(a).isNotEqualTo(b);
|
||||
assertThat(tokens.resolve(a)).isEqualTo(1L);
|
||||
tokens.revoke(a);
|
||||
assertThat(tokens.resolve(a)).isNull();
|
||||
assertThat(tokens.resolve(b)).isEqualTo(1L);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user