『博客开发日记-后台』之登录接口的实现

本文最后更新于 2026年3月27日 下午

登录接口的实现


登录接口的需求

和前台的登录接口差不多

先创建AdminAuthController类负责验证相关的接口(包括登录)


然后创建AdminAuthService接口


然后在UserLoginDto中新建captchaId和captchaCode两个字段


再创建创建AdminAuthVo类,里面包含token,refreshToken和expiresIn三个字段返回给前端


最后就是在AdminAuthServiceImpl类中实现相关功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// 后台管理系统登录认证
@Service
public class AdminAuthServiceImpl implements AdminAuthService
{
@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private RedisCache redisCache;

@Override
public ResponseResult login(UserLoginDto dto)
{
// 预防编程,用户名是否为空
if (!StringUtils.hasText(dto.getUsername())) {
// 提示 必须要传用户名
throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
}

// 验证码校验(如果提供了验证码)
if (StringUtils.hasText(dto.getCaptchaId()) && StringUtils.hasText(dto.getCaptchaCode())) {
String cacheKey = "captcha:" + dto.getCaptchaId();
String cachedCode = redisCache.getCacheObject(cacheKey);

if (cachedCode == null) {
throw new SystemException(AppHttpCodeEnum.CAPTCHA_EXPIRED);
}

if (!cachedCode.equalsIgnoreCase(dto.getCaptchaCode())) {
throw new SystemException(AppHttpCodeEnum.CAPTCHA_ERROR);
}

// 验证成功后删除验证码
redisCache.deleteObject(cacheKey);
}

// 将DTO转换为User实体
User user = BeanCopyUtils.copyBean(dto, User.class);

UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
Authentication authenticate = authenticationManager.authenticate(authenticationToken);

//判断是否认证通过
if (Objects.isNull(authenticate)) {
throw new RuntimeException("用户名或密码错误!");
}

//获取userid生成token
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
User userInfo = loginUser.getUser();
String userId = userInfo.getId().toString();

// 生成访问令牌
String token = JwtUtil.createJWT(userId);

// 生成刷新令牌(令牌有效时间为七天)
String refreshToken = JwtUtil.createJWT(userId, 7 * 24 * 60 * 60 * 1000L);

//把用户信息存入Redis (格式为 adminLogin:id,用于后台管理系统)
redisCache.setCacheObject("adminLogin:" + userId, loginUser);

// 构建响应对象
AdminAuthVo vo = new AdminAuthVo(token, refreshToken, JwtUtil.JWT_TTL / 1000);
return ResponseResult.okResult(vo);
}
}



PS:该系列只做为作者学习开发项目做的笔记用

不一定符合读者来学习,仅供参考


预告

后续会记录博客的开发过程

每次学习会做一份笔记来进行发表

“一花一世界,一叶一菩提”


版权所有 © 2026 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/


『博客开发日记-后台』之登录接口的实现
http://example.com/2026/03/25/『博客开发日记-后台』之登录接口的实现/
作者
云梦泽
发布于
2026年3月25日
更新于
2026年3月27日
许可协议