Linux 拨号vps windows公众号手机端

spring怎么获取当前登录的用户信息

lewis 8年前 (2017-02-25) 阅读数 9 #程序编程
文章标签 spring

在Spring中,可以通过使用Authentication对象来获取当前登录的用户信息。可以使用SecurityContextHolder.getContext().getAuthentication()方法来获取Authentication对象,然后通过getPrincipal()方法来获取用户信息。

以下是一个示例代码:

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class UserController {

    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof User) {
            return (User) authentication.getPrincipal();
        } else {
            // 用户未登录
            return null;
        }
    }
}

在上面的示例中,getCurrentUser()方法返回当前登录的用户对象,如果用户未登录,则返回null

需要注意的是,上述代码假设用户信息在Principal对象中,如果用户信息存储在其他地方,可以相应地进行调整。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门