我刚刚开始使用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??
}
}
答案 0 :(得分:2)
您可以通过以下方式获取当前Subject
的所有可用用户数据:
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资源(例如Account
和CustomData
):
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);
答案 1 :(得分:0)
如果你使用新的stormpath-servlet-plugin
,你只需要这样做:
Account account = AccountResolver.INSTANCE.getAccount(request);
通常,您可以在HttpServlet.doGet(...)
或doPost(...)
方法中对其进行调用。
有关详细信息,请参阅this Stormpath blog post。
然而,目前(2015年10月5日)如果您使用Shiro作为最新的stormpath-shiro-core
0.6.0
取决于{{1}与任何可用的stormpath-sdk-api
版本所需的版本不兼容的版本。
据推测,一旦他们发布插件的最终非RC版本,这将得到解决。
如果您查看博客帖子,full plugin documentation您可能决定您可以在没有Shiro的情况下做到。