Я только начал использовать Apache Shiro и Stormpath. В jsp все работает нормально и, как ожидалось. Но как я могу получить текущие данные пользователя и его пользовательские поля внутри сервлета?
@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 (например, Account
and 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);
Если вы используете новый stormpath-servlet-plugin
вам просто нужно сделать:
Account account = AccountResolver.INSTANCE.getAccount(request);
Обычно вы вызываете это в свой метод HttpServlet.doGet(...)
или doPost(...)
.
См. Это сообщение в блоге Stormpath для получения более подробной информации.
Однако в настоящее время (5 октября 2015 г.) немного беспорядок, если вы используете Shiro, поскольку последний stormpath-shiro-core
- 0.6.0
который зависит от stormpath-sdk-api
которая несовместима с той, которая требуется с помощью любой доступной stormpath-servlet-plugin
.
Предположительно, это будет устранено, как только они выпустят окончательную версию RC-версии, отличную от RC.
Если вы посмотрите на сообщение в блоге и полную документацию плагина, вы можете решить, хотя вы можете обойтись без Сиро.