简体   繁体   中英

Is there any standard way to deal with user privileges in Java?

I have a Java program involving several users who need to have different privileges. I currently have a class with basic CRUD methods; each of which requires that the current user has permission to call that method. For example, a user may have permission to call the "update" and "create" methods, but not "delete". All users have the ability to call the "read" method.

I'd like to give each user some arbitrary combination of permissions to use methods, so I think each method should check the users permission. However, what's the best way to do this? Should the user object be passed as a parameter into the methods each time they're called, or is there a better way? I've taken a look at the SecurityManager class in Java, but it appears to be targeted towards applets and file-system privileges (neither of which are applicable in my case). Is that correct, or have I missed something here?

Yes, you're looking for the java.security and javax.security.auth packages.

Basically what this framework gives you is a generic representation of principals (entities that can be authenticated; user or group), credentials (passwords, access keys, certificates), and permissions (aka permission sets or Access Control Lists).

But honestly this framework tends to complicate matters. IMO the only worthwhile convenience it provides is attaching security context to a thread using Subject.doAs() .

The basic gist of authentication is making sure someone is who they claim to be, and the basic gist of authorization is to let someone do only what they're allowed.

If you already have your own representations of users, passwords and permissions, I'd recommend you keep it simple. All you need to do is stash the user's ID and permissions as a single object in their session attributes and make this information available to your application's business logic for checking permissions (by passing as a parameter). It's simple, it's explicit, and it's highly testable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM