Showing posts from 2012

A basic implementation of basic access authentication using JASPIC

Basic access authentication is a crude mechanism to authenticate that's part of the HTTP standard. It allows both an agent to send username/password credentials and a server to request the agent to authenticate itself. This happens in a simple but standardized way. The mechanism can be easily implemented using Java EE's JASPIC and a sprinkle of utility code from the experimental OmniSecurity project (which is currently being discussed as one of the possible options to simplify security in Java EE 8). A basic implementation looks as follows: public class BasicAuthModule extends HttpServerAuthModule { @Override public AuthStatus validateHttpRequest(HttpServletRequest request, HttpServletResponse response, HttpMsgContext httpMsgContext) throws AuthException { String[] credentials = getCredentials(request); if (!isEmpty(credentials)) { UsernamePasswordIdentityStore identityStore = getReferenceOrNull(UsernamePa

Bridging Undertow's authentication events to CDI

Undertow's native security system has an incredible useful feature that's painfully missing in the security system of Java EE; authentication events . While Java EE applications could directly use the Undertow events, it's not directly clear how to do this. Furthermore having Undertow specific dependencies sprinkled throughout the code of an otherwise general Java EE application is perhaps not entirely optimal. The following code shows how the Undertow dependencies can be centralized to a single drop-in jar, by creating an Undertow extension (handler) that bridges the native Undertow events to standard CDI ones. Upon adding such jar to a Java EE application, the application code only has to know about general CDI events. First create the handler itself: import; import; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import javax.enterpris

Implementing container authentication in Java EE with JASPIC

This article takes a look at the state of security support in Java EE 6, with a focus on applications that wish to do their own authentication and the usage of the JASPI/JASPIC/JSR 196 API. Update: the further reading section has been moved to my ZEEF page about JASPIC . This contains links to articles, background, questions and answers, and more.   Declarative security is easy In Java EE it has always been relatively straightforward to specify to which resources security constraints should be applied. For web resources (Servlets, JSP pages, etc) there is the <security-constraint> element in web.xml, while for EJB beans there's the @RolesAllowed annotation. Via this so called 'declarative security' the programmer can specify that only a user having the given roles is allowed access to the protected web resource, or may invoke methods on the protected bean. The declarative model has a programmatic counterpart via methods like HttpServletRequest#isUserInR

Dynamic CDI producers

CDI has the well known concept of producers. Simply put a producer is a kind of general factory method for some type. It's defined by annotating a method with @Produces . An alternative "factory" for a type is simply a class itself; a class is a factory of objects of its own type. In CDI both these factories are represented by the Bean type . The name may be somewhat confusing, but a Bean in CDI is thus not directly a bean itself but a type used to create instances (aka a factory). An interesting aspect of CDI is that those Bean instances are not just internally created by CDI after encountering class definitions and producer methods, but can be added manually by user code as well. Via this mechanism we can thus dynamically register factories, or in CDI terms producers. This can be handy in a variety of cases, for instance when a lot of similar producer methods would have to be defined statically, or when generic producers are needed. Unfortunately, generics are not p

Counting the rows returned from a JPA query

Despite being almost ten years old, the JPA specification to this day has rather poor support for basic paging/sorting/filtering. Paging/sorting/filtering is used in a lot of (CRUD) applications where the result from a query is shown in a table, and where the user can scroll through the results one page at a time, and where this result can be sorted by clicking on any of the table column headers. In order to support this a number of things are generally needed: The total number of rows (or entities) in the full result must be known There should be support for an offset in the full result and a limit for the amount of rows that will be obtained The column (attribute) on which to sort must be dynamically added to the query Search expressions must be dynamically added to the query As it appears, only offset/limit is directly supported in JPA. A sorting column can only be added dynamically when using the overly verbose and hard to work with Criteria API. Search expressions

Simple Java based JSF 2.2 custom component

In JSF components play a central role, it being a component based framework after all. As mentioned in a previous blog posting , creating custom components was a lot of effort in JSF 1.x, but became significantly easier in JSF 2.0. Nevertheless, there were a few tedious things left that needed to be done if the component was needed to be used on a Facelet (which is the overwhelmingly common case); having a -taglib.xml file where a tag for the component is declared, and when the component's Java code resides directly in a web project (as opposed to a jar) an entry in web.xml to point to the -taglib.xml file. In JSF 2.2 these two tedious things are not needed anymore as the Facelets component tag can be declared using the existing @FacesComponent annotation . As an update to the original blog posting, a simple Java based custom component can be created as follows: components/ @FacesComponent(value = "components.CustomComponent", createTag

Fetching arbitrary object graphs in JPA 2

In Java EE, JPA (Java Persistence API) is used to store and retrieve graphs of objects. This works by specifying relations between objects via annotations (or optionally XML). Hand over the root of an object graph to the entity manager and it will persist it. Ask the entity manager for an object with a given Id and you'll get the graph back. This is all fine and well, but how in this model do we control which branches of the graph are retrieved and to which depth branches should be followed? The primary mechanism to control this with is the eager/lazy mechanism. Mark a relation as eager and JPA will fetch it upfront, mark it as lazy and it will dynamically fetch it when the relation is traversed. In practice, both approaches have their cons and pros. Mark everything eager and you'll risk pulling in the entire DB for every little bit of data that you need. Mark everything lazy, and you'll not only have to keep the persistence context around (which by itself can be trou

Hibernate's "Pure native scalar queries are not yet supported"

In JPA one can define JPQL queries as well as native queries. Each of those can return either an Entity or one or more scalar values. Queries can be created on demand at run-time from a String, or at start-up time from an annotation (or corresponding XML variant see Where to put named queries in JPA? ). Of all those combinations, curiously Hibernate has never supported named native queries returning a scalar result, including insert, update and delete queries which all don't return a result set, but merely the number of rows affected. It's a curious case, since Hibernate does support scalar returns in non-native named queries (thus a scalar return and named queries is not the problem), and it does support scalar returns in dynamically created native queries (thus scalar returns in native queries are not the problem either). An example of this specific combination: <named-native-query name="SomeName"> <query> INSERT INTO foo

Automatically setting the label of a component in JSF 2

In JSF input components have a label attribute that is typically used in (error) messages to let the user know about which component a message is. E.g. Name: a value is required here. If the label attribute isn't used, JSF will show a generated Id instead that is nearly always completely incomprehensible to users. So, this label is something you definitely want to use. Of course, if the label is going to be used in the error message to identify said component, it should also be rendered on screen somewhere so the user knows which component has that label. For this JSF has the separate <h:outputLabel> component, which is typically but not necessarily placed right before the input component it labels. The problem The thing is though that this label component should nearly always have the exact same value as the label attribute of the component it labels, e.g. <h:outputLabel for="username" value="Username" /> <h:inputText id="user