You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring社交登录集成报错:IllegalStateException(无当前登录用户)

Spring社交登录集成:ThreadLocal用户上下文丢失问题

我正在给Spring应用集成社交登录功能,之前已经解决了找不到Facebook Bean和ConnectionRepository这类错误——通过参考Spring Social Google示例里的SocialConfig等配置文件后有了进展,但现在卡到了一个新错误:

java.lang.IllegalStateException: No user is currently signed in

这个异常是SecurityContext.java里的getCurrentUser()方法抛出来的。明明我已经在SimpleSignInAdapter.signIn方法里设置了当前用户:针对Facebook用户用org.springframework.social.facebook.api.User,还执行了SecurityContext.setCurrentUser(new User(userId, null, null, null, null, null));。

错误发生在ConnectionRepository的connectionRepository方法调用SecurityContext.getCurrentUser()的时候,打印出来的值是null,直接触发了异常。我之前没怎么用过ThreadLocal,用起来有点懵,想问问有没有ThreadLocal的替代方案,或者其他能解决这个问题的办法。

下面是我的相关代码:

1. SecurityContext类

public final class SecurityContext { 
    private static final ThreadLocal<User> currentUser = new ThreadLocal<User>(); 
    private static Logger logger = LoggerFactory.getLogger(SecurityContext.class); 

    public static User getCurrentUser() { 
        User user = currentUser.get(); 
        if (user == null) { 
            throw new IllegalStateException("No user is currently signed in"); 
        } 
        return user; 
    } 

    public static void setCurrentUser(User user) { 
        currentUser.set(user); 
    } 

    public static boolean userSignedIn() { 
        return currentUser.get() != null; 
    } 

    public static void remove() { 
        currentUser.remove(); 
    } 
}

2. 设置ThreadLocal的SimpleSignInAdapter类

public final class SimpleSignInAdapter implements SignInAdapter { 
    private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator(); 

    public String signIn(String userId, Connection<?> connection, NativeWebRequest request) { 
        User user= new User(userId, null, null, null, null, null); 
        SecurityContext.setCurrentUser(user); 
        userCookieGenerator.addCookie(userId, request.getNativeResponse(HttpServletResponse.class)); 
        boolean flag = true; 
        if (flag) { 
            return "/signup"; 
        } 
        return null; 
    } 
}

3. SocialConfig中触发错误的connectionRepository方法

@Bean 
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) 
public ConnectionRepository connectionRepository() { 
    User user = SecurityContext.getCurrentUser(); 
    ConnectionRepository cr=usersConnectionRepository().createConnectionRepository(user.getId()); 
    logger.debug("cr==>"+cr); 
    return cr; 
}

内容的提问来源于stack exchange,提问作者rhazkoomar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:24:30