0

I would like to encapsulate Apache Shiro in a Servlet environment. I want to create MySecurityUtils and use Shiro SecurityUtils.getSubject in a static method. My question is whether this is a correct way to use SecurityUtils.getSubject method in a static method. Can this cause any problems in multithreaded servlet environment?

MySecurityUtils.java

import org.apache.shiro.subject.Subject;
import org.apache.shiro.SecurityUtils;

public class MySecurityUtils {

    public static MyUser getUser() {
        Subject currentUser = SecurityUtils.getSubject();
        MyUser myUser = new MyUser(currentUser);
        ...
    }
}

MyUser.java

public class MyUser {
   // ... constructors
   public boolean isPermitted(..) {subject.isPermitted(...)}
}
Koray Güclü
  • 2,857
  • 1
  • 34
  • 30

2 Answers2

0

I don't see why you would want to do this, but for your question's sake, this would be fine.

In a web context, Shiro's SecurityUtils#getSubject() returns a different Subject instance per request. Obviously if the subject is logged in, the credentials will be copied over (from session) to the new Subject instance. You are pretty much doing the same thing by returning a new MyUser instance on each call to getUser().

Careful though, if you call getUser() twice in the same request, you will get a different MyUser instance. However, the internal Subject will be the same. It can be problematic if you are doing logic other than delegating in your MyUser class.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • I would like to add additional application specific check to the MyUser object. MyUser will be immutable and the methods of the Subject method will be accesses via delagate methods. I think in that case it would be fine or? – Koray Güclü Mar 12 '13 at 15:10
  • Because you are returning a new instance each time from your `MySecurityUtils` class, careful if you need to get the User more than once per request. You will be operating on different `MyUser` instances. – Sotirios Delimanolis Mar 12 '13 at 15:26
0

After feedback of Sotirios I changed my code as follows

 public class SecurityHelper {
     public static boolean isAuthenticated(){
      Subject currentUser = SecurityUtils.getSubject();
      return currentUser.isAuthenticated();
     }
     public static void checkPermission(String permissionCode){
          Subject currentUser = SecurityUtils.getSubject();
          currentUser.checkPermission(permissionCode);
     }
     public static void checkPermission(String... permissionCodes){
          Subject currentUser = SecurityUtils.getSubject();
          currentUser.checkPermissions(permissionCodes);
     }
     ... and so on

I encapsulate all application logic in a Helper class.

Koray Güclü
  • 2,857
  • 1
  • 34
  • 30