获取shiro登录的用户名
【摘要】 获取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();
// ... 其他认证逻辑
}
}
注意事项
- 确保用户已经登录,否则
getPrincipal()
可能返回null - 如果使用自定义的Principal对象(不只是用户名),需要相应地转换类型
- 在多线程环境中,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)