1

我刚刚开始使用 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??
    }
}
4

2 回答 2

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 资源(如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);
于 2015-02-13T19:22:25.613 回答
0

如果你使用新的stormpath-servlet-plugin,你只需要这样做:

Account account = AccountResolver.INSTANCE.getAccount(request);

通常你会在你的HttpServlet.doGet(...)ordoPost(...)方法中调用它。

有关更多详细信息,请参阅此 Stormpath 博客文章

但是,如果您使用 Shiro,则目前(2015 年 10 月 5 日)有点混乱,因为最新stormpath-shiro-core版本0.6.0取决于stormpath-sdk-api与任何可用版本所需的版本不兼容的stormpath-servlet-plugin版本。

据推测,一旦他们发布插件的最终非 RC 版本,这将得到解决。

如果您查看博客文章和完整的插件文档,您可能会决定不使用 Shiro 也可以。

于 2015-10-05T18:02:03.203 回答