liusuyi
2026-06-11 b097f7539a7429a85cdda7959c9ecb83a37a2918
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
package com.ard.framework.security.handle;
 
import com.ard.common.constant.CacheConstants;
import com.ard.common.constant.Constants;
import com.ard.common.core.domain.model.LoginUser;
import com.ard.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
 
@Component
public class CustomAuthenticationSuccessHandler {
 
    @Value("${token.soloLogin}")
    private boolean soloLogin;
 
    @Autowired
    private RedisCache redisCache;
 
    @Autowired
    private ApplicationEventPublisher publisher;
 
    public void onAuthenticationSuccess(Authentication authentication) {
        // 允许多端登录,直接放行
        if (soloLogin) {
            return;
        }
        // 检查 Redis 中是否已有该用户登录
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getUserId();
 
        String key = CacheConstants.LOGIN_USERID_KEY + userId;
        if (redisCache.hasKey(key)) {
            throw new RuntimeException("用户已登录,请勿重复登录");
        }
        // 登录成功事件推送
        if (authentication != null && authentication.isAuthenticated()) {
            publisher.publishEvent(new AuthenticationSuccessEvent(authentication));
        }
    }
 
}