v0.2
This commit is contained in:
1 parent
e598ceaf5a
commit
68780851dd
10 files changed
+474
-12
No files matched your search
@@ -30,27 +30,75 @@
|
||||
<java.version>25</java.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<!-- Spring Boot Security 依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
<version>4.0.1</version>
|
||||
</dependency>
|
||||
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<!-- Spring Boot Starter 依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<!-- Spring Boot Web 依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- MyBatis-Plus 依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter-test</artifactId>
|
||||
<version>4.0.1</version>
|
||||
<scope>test</scope>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot4-starter</artifactId>
|
||||
<version>3.5.15</version>
|
||||
</dependency>
|
||||
<!-- MyBatis-Plus 分页插件模块 -->
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-jsqlparser</artifactId>
|
||||
<version>3.5.15</version>
|
||||
</dependency>
|
||||
<!-- java -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- mysql 依赖 -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<version>8.2.0</version> <!-- 或使用最新稳定版 -->
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- Lombok -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.30</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- Redis 依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<!-- JWT -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>0.12.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>0.12.6</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>0.12.6</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.tianze.www.config;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.lang.NonNull;
|
||||
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 com.tianze.www.entity.LoginUser;
|
||||
import com.tianze.www.util.JwtUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 旁路式 JWT 过滤器:
|
||||
* - 有合法 token → 把认证信息塞进 SecurityContext
|
||||
* - 无 token / token 无效 → 什么都不做,直接放行
|
||||
* - 从不抛异常、从不返回 401
|
||||
* 因此对现有 Controller 逻辑零影响。
|
||||
*/
|
||||
@Component //声明这是一个组件类,Spring 会自动扫描并注册为 Bean
|
||||
@RequiredArgsConstructor //自动生成构造函数,注入依赖
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String HEADER = "Authorization";
|
||||
public static final String PREFIX = "Bearer ";
|
||||
|
||||
private final JwtUtil jwtUtil;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain chain) throws ServletException, IOException {
|
||||
|
||||
// 预检请求不带 Authorization,直接放行
|
||||
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
String header = request.getHeader(HEADER);
|
||||
if (header != null && header.startsWith(PREFIX)) {
|
||||
LoginUser loginUser = jwtUtil.parse(header.substring(PREFIX.length()));
|
||||
if (loginUser != null
|
||||
&& SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
// 根据角色设置权限
|
||||
String role = loginUser.getRole() != null && loginUser.getRole() == "1"
|
||||
? "ROLE_ADMIN" : "ROLE_USER";
|
||||
var auth = new UsernamePasswordAuthenticationToken(
|
||||
loginUser, null, List.of(new SimpleGrantedAuthority(role)));
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
}
|
||||
}
|
||||
// 无论成功与否都继续,由 SecurityConfig 的授权规则裁决
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.tianze.www.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@MapperScan("cyou.tianshu.charging.mapper") // 扫描mapper接口
|
||||
public class MybatisPlusConfig {
|
||||
|
||||
/**
|
||||
* MyBatis-Plus插件配置
|
||||
*/
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
|
||||
// 分页插件
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
|
||||
// 乐观锁插件
|
||||
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
|
||||
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.tianze.www.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@Configuration //声明这是一个配置类
|
||||
@EnableWebSecurity //启用Spring Security的Web安全支持
|
||||
@RequiredArgsConstructor //自动生成构造函数,注入依赖
|
||||
public class SecurityConfig {
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
@Bean //声明一个名为filterChain的Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
// 1. 禁用CSRF(REST API不需要)
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
// 2. 启用跨域配置
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
// 3. 禁用所有Spring Security的安全功能
|
||||
//.authorizeHttpRequests(authz -> authz
|
||||
//.anyRequest().permitAll() // 允许所有请求,不做认证拦截
|
||||
//)
|
||||
// 4. 禁用HTTP Basic认证(重要!)
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
|
||||
// 5. 禁用表单登录
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
// 6. 禁用Session管理,改为无状态(重要!)
|
||||
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
|
||||
// ← 新增:把 JWT 过滤器插到用户名密码过滤器之前
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
|
||||
// ← 授权规则:两种模式二选一,见下文
|
||||
.authorizeHttpRequests(authz -> authz
|
||||
.requestMatchers("/apiForChargingStation/user/login", "/apiForChargingStation/user/register", "/error").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
|
||||
// ← 新增:统一 401,避免默认返回 HTML
|
||||
.exceptionHandling(ex -> ex.authenticationEntryPoint((req, res, e) -> {
|
||||
res.setStatus(401);
|
||||
res.setContentType("application/json;charset=UTF-8");
|
||||
res.getWriter().write("{\"code\":401,\"msg\":\"未登录或登录已过期\"}");
|
||||
}));
|
||||
|
||||
// 6. 禁用匿名用户
|
||||
//.anonymous(AbstractHttpConfigurer::disable);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 跨域配置 - 允许前端访问
|
||||
*/
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
|
||||
// 允许的来源(前端地址)
|
||||
configuration.setAllowedOrigins(Arrays.asList(
|
||||
"http://localhost:5173", // Vite开发服务器
|
||||
"http://localhost:3000", // 其他可能的端口
|
||||
"https://charging.tianshu.cyou" , // 生产环境可能的地址
|
||||
"https://charging.hong.email" ,
|
||||
"https://www.hong.email" // 生产环境可能的地址
|
||||
));
|
||||
|
||||
// 允许的HTTP方法
|
||||
configuration.setAllowedMethods(Arrays.asList(
|
||||
"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"
|
||||
));
|
||||
|
||||
// 允许的请求头(必须包含Authorization,因为你要传JWT)
|
||||
configuration.setAllowedHeaders(Arrays.asList(
|
||||
"Authorization", // JWT token在这里
|
||||
"Content-Type",
|
||||
"X-Requested-With",
|
||||
"Accept",
|
||||
"Origin",
|
||||
"X-Auth-Token", // 自定义token头(如果有)
|
||||
"X-User-Id" // 自定义用户ID头(如果有)
|
||||
));
|
||||
|
||||
// 暴露的响应头(让前端能访问)
|
||||
configuration.setExposedHeaders(Arrays.asList(
|
||||
"Authorization",
|
||||
"Content-Disposition" // 文件下载时需要
|
||||
));
|
||||
|
||||
// 是否允许发送凭证(cookies等)
|
||||
configuration.setAllowCredentials(true);
|
||||
|
||||
// 预检请求的缓存时间(秒)
|
||||
configuration.setMaxAge(3600L);
|
||||
|
||||
// 将配置应用到所有路径
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.tianze.www.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor // 添加无参构造函数
|
||||
@AllArgsConstructor // 添加全参构造函数
|
||||
@TableName("favorite_list")
|
||||
public class FavoriteList {
|
||||
@TableId
|
||||
private Long id;
|
||||
@TableField("user_id")
|
||||
private Long userId;
|
||||
@TableField("Latitude")
|
||||
private double latitude;
|
||||
@TableField("Longitude")
|
||||
private double longitude;
|
||||
@TableField("address")
|
||||
private String address;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.tianze.www.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 认证通过后放入 SecurityContext 的 principal。
|
||||
* 只放必要字段,不要放密码。
|
||||
*/
|
||||
@Data
|
||||
//@NoArgsConstructor// 无参构造函数
|
||||
@AllArgsConstructor// 全参构造函数
|
||||
public class LoginUser {
|
||||
private Long id;
|
||||
private String phone;
|
||||
private String role;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.tianze.www.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor // 添加无参构造函数
|
||||
@AllArgsConstructor // 添加全参构造函数
|
||||
@TableName("smart_charging_user")
|
||||
public class UserInfo {
|
||||
@TableId(type=IdType.AUTO)
|
||||
private Long id;// 用户ID
|
||||
@TableField("name")
|
||||
private String name;// 用户名
|
||||
@TableField("email")
|
||||
private String email;// 用户邮箱
|
||||
@TableField("password")
|
||||
private String password;// 用户密码
|
||||
@TableField("role")
|
||||
private String role;// 用户角色
|
||||
@TableField("created_at")
|
||||
private java.time.LocalDateTime created_at;// 创建时间
|
||||
@TableField("updated_at")
|
||||
private java.time.LocalDateTime updated_at;// 更新时间
|
||||
@TableField("phone")
|
||||
private String phone;// 用户手机号
|
||||
@TableField("car_type")
|
||||
private String carType;// 用户车型
|
||||
@TableField("car_brand")
|
||||
private String carBrand;// 用户车品牌
|
||||
public UserInfo(String username, String password) {
|
||||
this.name = username;
|
||||
this.password = password;
|
||||
}
|
||||
public UserInfo(String username, String password, String phone) {
|
||||
this.name = username;
|
||||
this.password = password;
|
||||
this.phone = phone;
|
||||
}
|
||||
public UserInfo(Long id, String phone, String role) {
|
||||
this.id = id;
|
||||
this.phone = phone;
|
||||
this.role = role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.tianze.www.util;
|
||||
|
||||
import com.tianze.www.entity.LoginUser;
|
||||
import com.tianze.www.entity.UserInfo;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
|
||||
@Component
|
||||
public class JwtUtil {
|
||||
|
||||
private final SecretKey key;
|
||||
private final long expireMillis;
|
||||
|
||||
public JwtUtil(@Value("${jwt.secret}") String secret,
|
||||
@Value("${jwt.expire-minutes:120}") long expireMinutes) {
|
||||
// 要求 secret 至少 32 字节,否则抛 WeakKeyException
|
||||
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
|
||||
this.expireMillis = expireMinutes * 60_000L;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录成功后调用,用你的 User 实体签发 token。
|
||||
* 不修改 User 实体,不修改登录逻辑。
|
||||
*/
|
||||
public String generate(UserInfo user) {
|
||||
Instant now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.subject(String.valueOf(user.getId()))
|
||||
.claim("phone", user.getPhone())
|
||||
.claim("role", user.getRole())
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(now.plusMillis(expireMillis)))
|
||||
.signWith(key) // 默认 HS256,密钥长度决定算法
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析失败(过期 / 签名错 / 格式错)统一返回 null。
|
||||
* 让调用方(过滤器)保持"静默失败"语义,不抛异常。
|
||||
*/
|
||||
public LoginUser parse(String token) {
|
||||
try {
|
||||
Claims c = Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
|
||||
String role = c.get("role", String.class); // JSON 数字反序列化可能是 Integer 或 Long
|
||||
return new LoginUser(
|
||||
Long.valueOf(c.getSubject()),
|
||||
c.get("phone", String.class),
|
||||
role == null ? null : role);
|
||||
} catch (JwtException | IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 取剩余有效毫秒数,供 Redis 黑名单设置 TTL 用 */
|
||||
public long remainingMillis(String token) {
|
||||
try {
|
||||
Date exp = Jwts.parser().verifyWith(key).build()
|
||||
.parseSignedClaims(token).getPayload().getExpiration();
|
||||
return Math.max(0, exp.getTime() - System.currentTimeMillis());
|
||||
} catch (Exception e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.tianze.www.util;
|
||||
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class PasswordUtil {
|
||||
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
|
||||
public String encodePassword(String rawPassword) {
|
||||
return passwordEncoder.encode(rawPassword);
|
||||
}
|
||||
|
||||
public boolean matches(String rawPassword, String encodedPassword) {
|
||||
return passwordEncoder.matches(rawPassword, encodedPassword);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,20 @@
|
||||
spring:
|
||||
application:
|
||||
name: demo
|
||||
datasource:
|
||||
#url: jdbc:mysql://81.70.228.227:3306/smart_charging_table?&characterEncoding=UTF-8&connectionTimeZone=Asia/Shanghai
|
||||
url: jdbc:mysql://192.168.1.21:3306/smart_charging_table?&characterEncoding=UTF-8&connectionTimeZone=Asia/Shanghai
|
||||
username: root
|
||||
password: 12345Wcvff
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
hikari:
|
||||
maximum-pool-size: 10
|
||||
minimum-idle: 5
|
||||
idle-timeout: 600000
|
||||
connection-timeout: 30000
|
||||
max-lifetime: 1800000
|
||||
jwt:
|
||||
secret: wddadsadwsadawdsfdsfdfjfndfdwdasdwdadwdsdwd
|
||||
expiration-minutes: 120
|
||||
server:
|
||||
port: 8080
|
||||
Reference in new issue
Block a user