集成spring security和jwt验证
parent
8f94a6022f
commit
fe32142027
@ -0,0 +1,6 @@
|
||||
package com.supervision.ai.service.hub.constant;
|
||||
|
||||
public class UserConstant {
|
||||
public static final String USER_STATUS_ENABLED = "1"; // 用户状态启用
|
||||
public static final String USER_STATUS_DISABLED = "0"; // 用户状态禁用
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.supervision.ai.service.hub.controller;
|
||||
|
||||
import com.supervision.ai.service.hub.service.impl.AuthService;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
|
||||
try {
|
||||
String token = authService.login(request.getUsername(), request.getPassword());
|
||||
Map<String, String> response = new HashMap<>();
|
||||
response.put("token", token);
|
||||
return ResponseEntity.ok(response);
|
||||
} catch (RuntimeException e) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class LoginRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.supervision.ai.service.hub.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.supervision.ai.service.hub.domain.SysUser;
|
||||
import com.supervision.ai.service.hub.mapper.SysUserMapper;
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static com.supervision.ai.service.hub.constant.UserConstant.USER_STATUS_DISABLED;
|
||||
import static com.supervision.ai.service.hub.constant.UserConstant.USER_STATUS_ENABLED;
|
||||
|
||||
@Service
|
||||
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> implements UserDetailsService {
|
||||
|
||||
/**
|
||||
* 根据用户名加载用户信息
|
||||
* Spring Security 会调用该方法来获取用户信息
|
||||
*
|
||||
* @param username 用户名
|
||||
* @return UserDetails
|
||||
* @throws UsernameNotFoundException 用户名未找到异常
|
||||
*/
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
SysUser user = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
|
||||
if (user == null) {
|
||||
throw new UsernameNotFoundException("用户不存在: " + username);
|
||||
}
|
||||
if (USER_STATUS_DISABLED.equals(user.getStatus())) {
|
||||
throw new DisabledException("用户已被禁用");
|
||||
}
|
||||
// 将查询到的用户信息组装成UserDetails对象
|
||||
// **扩展点**:如需加载用户角色权限,可在此处查询 sys_user_role 表关联的角色,并将角色加入 authorities 列表
|
||||
List<GrantedAuthority> authorities = Collections.emptyList();
|
||||
// 使用Spring Security提供的User对象作为UserDetails返回
|
||||
return new User(user.getUsername(), user.getPassword(), authorities);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
package com.supervision.ai.service.hub.util;
|
||||
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jws;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
|
||||
@Value("${jwt.secret}")
|
||||
private String Secret;
|
||||
|
||||
@Value("${jwt.expiration}")
|
||||
private long Expiration; // 1天
|
||||
|
||||
private SecretKey secretKey;
|
||||
|
||||
@PostConstruct
|
||||
public void initKey() {
|
||||
this.secretKey = Keys.hmacShaKeyFor(Base64.getDecoder().decode(Secret));
|
||||
}
|
||||
|
||||
// 生成Token
|
||||
public String generateToken(UserDetails userDetails) {
|
||||
return Jwts.builder()
|
||||
.subject(userDetails.getUsername())
|
||||
.issuedAt(new Date())
|
||||
.expiration(new Date(System.currentTimeMillis() + Expiration))
|
||||
.signWith(secretKey, Jwts.SIG.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
// 从 Token 中解析用户名
|
||||
public String getUsernameFromToken(String token) {
|
||||
Jws<Claims> jws = Jwts.parser()
|
||||
.verifyWith(secretKey)
|
||||
.build()
|
||||
.parseSignedClaims(token);
|
||||
return jws.getPayload().getSubject();
|
||||
}
|
||||
|
||||
|
||||
// 校验Token是否有效
|
||||
public boolean validateToken(String token, UserDetails userDetails) {
|
||||
try {
|
||||
String username = getUsernameFromToken(token);
|
||||
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 判断是否过期
|
||||
private boolean isTokenExpired(String token) {
|
||||
Jws<Claims> jws = Jwts.parser()
|
||||
.verifyWith(secretKey)
|
||||
.build()
|
||||
.parseSignedClaims(token);
|
||||
return jws.getPayload().getExpiration().before(new Date());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue