Wednesday, January 16, 2013

Servlet 3.0 ( Security ) ...........3

3.) Dynamic Security :
Dynamic Servlet Security Annotations @DeclareRoles("role1","role2")  & @RunAs("rolename")
above 2 annotations can be given at the time of context initialization ( while servlets are registered dynamically) 
in Servlet3.0 interface ServletRegistration.Dynamic has below imp methods 


 void setLoadOnStartup(int loadOnStartup)
          Sets the loadOnStartup priority on the Servlet represented by this dynamic ServletRegistration.
 void setMultipartConfig(MultipartConfigElement multipartConfig)
          Sets the MultipartConfigElement to be applied to the mappings defined for this ServletRegistration.
 void setRunAsRole(java.lang.String roleName)
          Sets the name of the runAs role for this ServletRegistration.
 java.util.Set setServletSecurity(ServletSecurityElement constraint)
          Sets the ServletSecurityElement to be applied to the mappings defined for this ServletRegistration.

Check web for more examples

4.) HttpOnly cookie and tags are supported ..refer  servlet 3.0 specs.
HttpOnly cookies indicate to the client that they should not be exposed to client-side scripting code (It’s not filtered out unless the client knows to look for this attribute). The use of HttpOnly cookies helps mitigate certain kinds of cross-site scripting attacks.

Servlet 3.0 ( Security ) ...........2

2. ) Use of Annotations :
@ServletSecurity & @Inherited

We can define all security configuration in DD by use of annotations while creating a servlet.
for @ServletSecurity @WebServlet must be given with attribute urlPatterns [ else it will take as per defined in DD]. example

Only guest is allowed without  any transport layer authentication check

@WebServlet(urlPattern="/secureServlet")
@ServletSecurity ( 
           @ HttpConstraint ( rolesAllowed={"guest"}, transport.Guarantee=TransportGaurantee.NONE) )

-------------------------------------------------------------------------
No user is allowed
@ServletSecurity ( EmptyRoleSemantic.DENY  )

-------------------------------------------------------------------------
All roles are allowed for all methods ; GET/POST only for guest user ; for Post transport layer needs to authenticated.
@ServletSecurity ( 
           httpConstraint ={
@HttpMethodConstraint(value="GET", rolesAllowed="guest")
@HttpMethodConstraint(value="POST", rolesAllowed="guest",                                                                                                                               transport.Guarantee=TransportGaurantee.CONFIDENTIAL)
                                    } )

-------------------------------------------------------------------------
All methods can be accessed only by role of guest ; TRACE is denied for all.
@ServletSecurity ( 
           httpConstraint ={
@HttpMethodConstraint(value="TRACE", EmptyRoleSemantic.DENY )
@HttpMethodConstraint( rolesAllowed="guest")
                                    } )
-------------------------------------------------------------------------

@Inherited

If superclass has provided annotation @ServletSecurity by default all its subclasses will inherit  its Secirity contraints by the rules defined by @Inherited annotation.
If subclass provided its own @SS constraint then it will override base classes SS constraints.

Servlet 3.0 ( Security ) ............1

In Servlet 3.0 use of annotations has made  ease to provide security. through annotations one can provide security dynamically  at the time of  servlet registration. Key features  on which servlet 3.0 security is based are listed below.
1) Authentication methods
2) Annotations
3) HttpOnly cookie (also SSO for which i have not much idea)
4) Http method Ommision tag
* Before 3.0 one has to map security  configuration in DD ( web.xml ) , but in 3.0 use of annotations is enriched. Here a snap shot of servlet security is given ( that is not sufficient but necessary to know )

1) Authentication methods: HttpServletRequest has 3 imp methods that can check / validate user .
boolean authenticate(HttpServletResponse response)
          Use the container login mechanism configured for the ServletContext to authenticate the user making this request.
 java.security.Principal getUserPrincipal()
          Returns a java.security.Principal object containing the name of the current authenticated user.
 boolean isRequestedSessionIdFromCookie()
          Checks whether the requested session ID came in as a cookie.


 boolean isRequestedSessionIdFromURL()
          Checks whether the requested session ID came in as part of the request URL.
 boolean isRequestedSessionIdValid()
          Checks whether the requested session ID is still valid.
 boolean isUserInRole(java.lang.String role)
          Returns a boolean indicating whether the authenticated user is included in the specified logical "role".
 void login(java.lang.String username, java.lang.String password)
          Validate the provided username and password in the password validation realm used by the web container login mechanism configured for the ServletContext.
 void logout()
          Establish null as the value returned when getUserPrincipal, getRemoteUser, and getAuthType is called on the request.



       

Sunday, January 13, 2013

Web Listeners ( Servlets/Session)

There are 7 Listeners that are important  for servlet and session 

1 . ServletContextListener
public void contextDestroyed(ServletContextEvent arg0) {}
public void contextInitialized(ServletContextEvent arg0) {}

2. SessionListener / HttpSessionListener
sessionCreated(HttpSessionEvent evt ){}
sessionDestroyed(HttpSessionEvent evt) {}

HttpSessionActivationListener
sessionDidActivate(HttpSessionEvent ) {}
sessionWillPassivate(HttpSessionEvent ) {}


3. ServletContextAttributeListener / HttpSessionAttributeListener / ServletRequestAttributeListener 
attributeAdded()
attributeRemoved()
attributeReplaced()
in attributelistener the argument to the methods will be different as per the  interface.
for HttpSessionAttributeListener arg will be HttpSessionSessionBindingEvent.

4. HttpSessionBindingListener will be implemented by attribute
valuebound(HttpSessionBindingListener )
valueunbound(HttpSessionBindingListener )



 



Monday, January 7, 2013

Servlet 3.0

With the advent pf 3.0 drastic change has come while working with  servlets . J2EE 6  has many changes .
Few imp changes are 

  • No need of having 1 big web.xml .instaed multiple web-fragment.xml can be there
  • Dynamic registration of servlets , filters
  • Use of annotations


Here i am putting few important annotations provided by specs servlet 3.0  .


@WebServlet
(asyncSupported = false, name = "HelloServlet", urlPatterns = {"/hello"},
initParams = {@WebInitParam(name="param1", value="value1"), 
@WebInitParam(name="param2", value="value2")}
)
 
 public class TestServlet extends javax.servlet.http.HttpServlet { 
    ....   } 
----------------------------------------------------------  
 @WebFilter
(urlPatterns={"/myurl"},
   initParams={ @InitParam(name="mesg", value="my filter") }) 
  public class TestFilter implements javax.servlet.Filter {
        ....
        public void init(FilterConfig filterConfig) throws ServletException {   
      
   ....   }

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            ....
        }

        public void destroy() {
            ....
        }
    }
---------------------------------------------------------

@WebServletContextListener
    public class TestServletContextListener implements javax.servlet.ServletContextListener {
        ....
        public void contextInitialized(ServletContextEvent sce) {
            ....
        }

        public void contextDestroyed(ServletContextEvent sce) {
            ....
        }
    } 

---------------------------------------------------------

@MultipartConfig(location="c:\\tmp", fileSizeThreshold=1024*1024,
 maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
 
Above annotation can be used along with @WebServlet
 
For ordering of Filter  / Servlets  < absolute - ordering > tag 
should be configured in web.xml
 

Tuesday, November 27, 2012

JSP (EL Implicit Objects)

  Identifier               Description

 pageContext          PageContext instance
 pageScope             Map-associates name and values of page-scoped attributes
 requestScope         Map-associates name and values of request-scoped attributes
 sessionScope         Map-associates name and values of session-scoped attributes
 applicationScope    Map-associates name and values of application-scoped attributes  parameters
 param                   Map-stores the primary values of the request parameters by name
 paramValues          Map-stores all values of the request parameters as String arrays
 header                  Map-stores the primary values of the request headers by name
 headerValues         Map-stores all values of the request headers as String arrays
 cookie                   Map-stores the cookies accompanying the request by name
 initParam              Map-stores the context initialization params of the appln by name

Wednesday, November 7, 2012

Java Tidbits .......................... ( Riding over Methods )

Method Overriding is form of Polymorphism . Since which method to be called will be  resolved at runtime  by the  object assigned to reference.

Rules for overriding are :

  • A method if overridden in subclass should have same argument.
  • same or  extended return type(Covariant)
  • arguments can be declared as final additionally in subclass provided the datatype is same .
  • can throw checked exception if base class method too throws the checked exception .
  • the exception thrown can be  either same or subclass of  thrown exception in base method.
  • // Rule hold only for checked exception 
  • Access modifiers can make it less restrictive, but not more restrictive.
Field Hiding
A subclass cannot override fields of the superclass, but it can hide them by declaring  with same name .
if  want to access  base class's field then  user super to invoke  field .

While implementing interfaces all above rules are applicable for overriding interface declared methods too.
Exception and return of covariant types are applicable .

Can a private method be overridden by a subclass?
NO! Since the subclass,  cannot inherit a private method, it therefore cannot override the method—overriding depends on inheritance.