gpt4 book ai didi

java - Shiro + Stormpath 获取 servlet 中的当前用户

转载 作者:行者123 更新时间:2023-11-30 03:33:33 26 4
gpt4 key购买 nike

我刚刚开始使用 Apache Shiro 和 Stormpath。在 jsp 中,一切都工作正常并且符合预期。但是如何在 servlet 中获取当前用户数据及其自定义字段呢?

@WebServlet("/test")
public class Foo extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();

// how to get username and custom fields hereg??
}
}

最佳答案

您可以通过以下方式获取当前主题的所有可用用户数据:

Map<String, String> userAttributes = SecurityUtils.getSubject().getPrincipals().oneByType(java.util.Map.class);
System.out.println("Account href: " + userAttributes.get("href"));
System.out.println("Username: " + userAttributes.get("username"));
// other attributes available

如果您还想操作实际的 Stormpath 资源(例如 AccountCustomData):

ApplicationRealm realm = ((ApplicationRealm)((RealmSecurityManager) SecurityUtils.getSecurityManager()).getRealms().iterator().next());
Client client = realm.getClient(); //The Client object is what allows you to communicate with Stormpath
Account account = client.getResource(userAttributes.get("href"), Account.class); //The actual Stormpath Account object belonging to the current Subject
CustomData customData = account.getCustomData();
//or, if you want to obtain the CustomData without first retrieving the Account, thus avoiding an unnecessary server hit:
//CustomData customData = client.getResource(userAttributes.get("href") + "/customData", CustomData.class);

关于java - Shiro + Stormpath 获取 servlet 中的当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28497239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com