Search code examples
javaservletsshirostormpath

Shiro + Stormpath get current user in servlet


I have just started to use Apache Shiro and Stormpath. In the jsp's everything is working fine and as expected. But how can I get the current user data and his custom fields within a 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??
    }
}

Solution

  • You can get all the available user data for the current Subject this way:

    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
    

    In case you also want to manipulate actual Stormpath Resources (like 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);