Shiro + Stormpath 在servlet中获取当前用户

Shiro + Stormpath get current user in servlet

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

您可以通过以下方式获取当前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);

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

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

通常您会在 HttpServlet.doGet(...)doPost(...) 方法中调用它。

有关详细信息,请参阅 this Stormpath blog post

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

据推测,一旦他们发布了插件的最终非 RC 版本,这个问题就会得到解决。

如果您查看博客 post 和 full plugin documentation,您 可能 决定没有 Shiro 也可以。