users@jersey.java.net

ResourceFilter best practices: Exception mapping, setting custom security context and passing auth context

From: Mahesh Venkat <mhvenkat_at_gmail.com>
Date: Sun, 27 Dec 2009 19:03:49 -0800

Hi,

I am trying to define best practices for using Resourcefilters in areas like
exceptions, setting custom security context and passing authorization
context.

Here is sample code:

a) *Exceptions*: Should we throw exception in Resourcefilters or capture
them as Error entities and set them in CointainerResponse or HttpContext.
I wrote a ResourceFilter to handle oauth validation and throw an exception
for invalid credentials. I am observing that the exceptions thrown in the
resourcefilter aren't mapped to any exceptions in the ExceptionMapper. Here
is my code snippet:

            /* -------------override methods of ResourceFilter
---------------------------------*/
            @Override
            public ContainerRequestFilter getRequestFilter() {

                try
                {
                    context = RestInterceptor.restAuthContext (httpRequest,
httpResponse);
                    usrContext = context.getUserContext();
                    if (usrContext == null){
                        logger.log(Level.INFO, "ResourceFilterFactory :
RestFilter : getRequestFilter: UserContext is NULL ");
                        throw new MappableContainerException(new
InvalidCredentialException(" Invalid User Context or Session "));
                    }
                } catch (Exception exc) {

                        throw new MappableContainerException (new
InvalidCredentialException(" Unable to retrieve User Context "));
                }
                logger.log(Level.INFO, "ResourceFilterFactory : RestFilter :
getRequestFilter : set Yodlee UserContext as a http request attribute");
                httpRequest.setAttribute(CommonDefs.USER_CONTEXT,
usrContext);
                httpRequest.setAttribute(CommonDefs.CONTEXT, context);
                logger.log(Level.INFO, "ResourceFilterFactory : RestFilter :
getRequestFilter : set RestSecurityContext in ContainerRequest ");
                containerRequest.setSecurityContext(new
RestSecurityContext(usrContext));
               return this;
            }

b)* For positive cases:* if we set custom securitycontext in the
ContainerRequest or HttpContext is it available in the resource methods when
referred to by @Context SecurityContext?
I would like to retrieve the custom securitycontext in a resource method.
From the custom securitycontext I want to extract the authorization context
set in a custom Principal object.

*Alternatively: *
c) pass a validated authorization context as attributes in
HttpServletContext or use setParameters?


Regards
--Mahesh