Java Web Service - Secure web methods by user
Java web service, is it possible to expose different methods to different user?
For example, I have 10 methods in my 开发者_JAVA技巧web service but I want to allow user A access to 1 or 2 methods only, how can this be done?
I guess you can not completely hide the methods from the user. The only thing you can do is to provide only required information to the specific User. In one my application I have implemented this by using Decorate Design Pattern. I will try to explain it.
You can separate this logic in some non-webservice class. Create 2 web services (one for each userAccess Model). Call the separated logic from each of the web service.
Say you have created class CommonA which contains methods 1 ~10. Create web service say ForUserA this contains method 1 and 2 only which calls method 1 and 2 of CommonA. and so on.
It will be a great pleasure if anyone suggest the better way to do this.
In order for your webservice to determine which user is currently calling your webservice method, you need some kind of authentication.
Since both SAOP & REST use HTTP protocol, you can use sessions. Once your client has authenticated himself, you can allow/deny him access to any webmethod you like.
Here is an easy example for a SOAP service.
@Resource WebServiceContext wsContext;
MessageContext mc = wsContext.getMessageContext();
HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
String username = (String)session.getAttribute("username");
if(username.equals("userA") {
// Do your thing
} else {
throw new WebServiceException("Not allowed to access this method.");
}
精彩评论