获取shiro登录的用户名

举报
林欣 发表于 2025/05/23 17:33:17 2025/05/23
【摘要】 获取Shiro登录的用户名在Apache Shiro中,可以通过以下几种方式获取当前登录用户的用户名: 1. 使用SecurityUtilsimport org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;// 获取当前SubjectSubject currentUser = SecurityUtil...

获取Shiro登录的用户名

在Apache Shiro中,可以通过以下几种方式获取当前登录用户的用户名:

1. 使用SecurityUtils

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

// 获取当前Subject
Subject currentUser = SecurityUtils.getSubject();

// 检查用户是否已认证
if (currentUser.isAuthenticated()) {
    // 获取用户名
    String username = currentUser.getPrincipal().toString();
    System.out.println("当前登录用户: " + username);
} else {
    System.out.println("用户未登录");
}

2. 在Controller中获取(Spring MVC环境)

import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
    
    @RequestMapping("/userinfo")
    public String getUserInfo() {
        String username = SecurityUtils.getSubject().getPrincipal().toString();
        System.out.println("当前用户: " + username);
        return "userPage";
    }
}

3. 使用注解方式(需要Shiro注解支持)

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    
    @GetMapping("/currentUser")
    @RequiresAuthentication
    public String getCurrentUser() {
        return SecurityUtils.getSubject().getPrincipal().toString();
    }
}

4. 在自定义Realm中获取

如果你需要在Realm中获取当前用户信息:

public class MyRealm extends AuthorizingRealm {
    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户名
        String username = (String) token.getPrincipal();
        // ... 其他认证逻辑
    }
}

注意事项

  1. 确保用户已经登录,否则getPrincipal()可能返回null
  2. 如果使用自定义的Principal对象(不只是用户名),需要相应地转换类型
  3. 在多线程环境中,Shiro的Subject是线程绑定的,确保在正确的线程中获取

自定义Principal对象

如果你使用了自定义的Principal对象(不只是存储用户名):

public class UserPrincipal implements Principal {
    private String username;
    private Long userId;
    // getters and setters
    
    @Override
    public String toString() {
        return username;
    }
}

// 获取时
UserPrincipal principal = (UserPrincipal) SecurityUtils.getSubject().getPrincipal();
String username = principal.getUsername();

以上方法都可以帮助你获取当前通过Shiro登录的用户名。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。