Introduce to Winter Security

Winter Security is one of the most important components of Winter Framework. It enhances security constraints adopted by the server application and eases development in the best possible ways. Developing web services with Winter Security can really simplify the security logic and reduce boilerplate code without giving up the flexibility of the program.

Prerequisites

To be able to understand Winter Security, you need to know Java EE architecture since Winter is a complement for Java EE in the security aspect. If you don’t know Java EE architecture, the official tutorial would be a perfect starting point. To be more specific, the security part is relatively more important. In addition, knowledges of database, basic Java concepts and build tools are expected, e.g. SQL, Java project build path, Apache Maven, etc.
If you want to give a shot with limited knowledge in Java EE, it is OK. Once you have basic exposure to Java web, e.g. Servlet, JSP, etc., you should still be able to setup Winter Security by reading this blog. A nice thing about Winter Security is the simplicity it provides, which makes it to automatically fit in your project and start working behind the scene.

What does Winter Security do for you?

Winter Security provides authentication and authorization services for Java EE web applications. Authentication service is to exam if a user is whom he said who he is. Accordingly, authorization service is to exam if a user has the permissions to access what needs those permissions.

Why to use Winter Security over others?

Most of security frameworks are complex because they aim to provide general solutions to all development scenarios. Moreover, some older frameworks do not have a design to suit modern needs. Although, Winter Security requires a moderate understanding of Java EE platform, it still is a light weight and fairly easy to use security framework. In addition, most Java developers already know very well about Java EE platform anyway, there is no barrier for them to employ Winter Security as a light weight security framework.
Winter Security also summarizes other frameworks and adopts concepts such as User-Role-Permission authorization, Security Realm, Customizable Handlers, etc. These features make Winter Security strong enough to handle most web development needs.

Conditions of using Winter Security

Winter Security depends on Java EE 7 technologies. It means your project must be a Java EE project, and it ought to be deployed to a Java EE 7 Full Platform Compatible Implementations, e.g. GlassFish, Jboss, etc.

Concepts of Winter Security

Before start installing Winter Security, you have to understand some of the basic concepts of web security. Most security frameworks, including Winter Security are following the similar structure. There are 3 concepts to know in the first place:
1. User-Role-Permission authorization;
2. Security Realm;
3. Customizable Handlers.

User-Role-Permission authorization

User-Role-Permission (URP) authorization is one of many routes to connect users and permissions in order to authorize particular permissions to certain users through their roles. Not every security framework supports this 3-step authorization connection. For example, Java EE only have User-Role authorization. Thus, all the functionalists are statically bonded to the particular roles in the code. Whereas, URP can be dynamic. By assigning permissions to the method level, any privileged users can maintain Role-Permission relationship without changing the existing code.

Security Realm

A Security Realm is a mechanism to protect the resources of your application. In Winter Security, system can retain user credentials, roles, and permissions from a particular realm. It connects to an authentication and authorization information provider, such as a database or file system. By default, Winter Security uses a JdbcRealm to connect database. You can write your own Realm by implementing the Realm interface.

Customizable Handlers

Customizable Handlers are the ways to define certain actions during an authentication and authorization process. There are 3 types of Handlers in Winter Security: AuthenticationContextHandler (AECH), AuthenticationExceptionHandler (AEEH), and AuthorizationExceptionHandler (AOEH). AECH collects user credentials of an incoming request. AEEH tells what to do if a user is not authenticated. AOEH tells what to do if a user attempts to access non-permitted method.

Authentication and authorization workflow

A typical workflow of an authentication and authorization process starts at collecting user credentials using AECH. The user credentials then being stored in an AuthenticationContext**. Once the request hits a method that requires certain permission, an AuthorizationInterceptor will exam the user credentials in AuthenticationContext with user information provided by the Security Realm. If everything is OK, the user then is permitted to access the method. Otherwise, depending on what problems are, AEEH or AOEH will be called to handle the situations.

Install Winter Security for your project

In order to use Winter Security, you need to build your project with related libraries including Winter Core and Winter Security. There are 2 ways of doing this:
1. Download .jar files and include them into your project’s build path: winter-core, winter-security.
2. Use Maven build tool to declare Winter Security dependency* in the pom.xml file:

<project>
    ...
    <dependencies>
        ...
        <dependency>
            <groupId>ca.ljz</groupId>
            <artifactId>winter-security</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        ...
    </dependencies>
    ...
</project>

Once you done one of the above options, Winter Security will be activated for your project right away.

Configurations

Winter Security follows an idea of convention over configuration to minimize configurations setting. However, you still have to have a configuration file and at least point out which data source to be used to retrieve user information.
Once you have Winter Security installed on your project, it is activated. If you run your project right away, you will get an error saying there is no data source connected. That is exact what we should get. Winter Security by default uses a JdbcRealm to retrieve user information from a database. You could either write your own Realm by implementing Realm interface, or indicate a data source in the configuration file. You can explore more about writing a Realm in the Java Doc. Instead of writing one, I am going to talk more about configurations with the default JdbcRealm.

application.properties

In order to configure Winter Security, you need to create a text file named application.properties in your default package (known as default directory of the project classloader). If you don’t know where default package is, just create a new class in your IDE with empty package entry. The new class will be created in the default package of your project. That folder is where to store your application.properties file.
The configuration file, application.properties, is a key-value paired text file to be loaded by java.util.Properties. Thus, it should follow the standard format of key-value property file. In Winter sample project, you can find all predefined keys and their default values in the configuration file as an example.

DataSource property

To specify a data source, you need to assign the JNDI name of the data source to “DataSource” key/property, e.g. DataSource=jdbc/sample. The JNDI name should have been predefined in your application server.
You don’t need other lines in application.properties file unless you want to customize other properties. Now, you have had one line key-value pair of DataSource property, your project should be able to start again normally.

Conventions for table structure

In previous sections, we talked about URP (User-Role-Permission) authorization. To support this feature, the database tables should be created following this structure. As a suggestion, 5 tables would be involved in authentication and authorization progress: user, user_role, role, role_permission, permission. From the table naming convention, you would know that user_role and role_permission are bridging tables for many-to-many relationships between user, role, and permission tables.
To use the default JdbcRealm, you should either have exact same naming for tables and columns to match the predefined SQL queries, or, you can specify queries in the configuration file.
To specify queries, you need define values for 3 keys/properties in application.properties file: Query.Password, Query.Role, and Query.Permission.

Query.Password property

You need a sql query that takes a username to get the associated password. E.g. Query.Password=select password from user where username = ?

Query.Role property

This property demands a username and returns a set of roles. E.g. Query.Role=select role from user_role where username = ?

Query.Permission property

By searching across user_role and role_permission tables, this query is to find all permissions of a given user. E.g. Query.Permission=select permission from user_role ur, role_permission rp where ur.role = pr.role and ur.username = ?
Depending on your actual table naming and structure, the queries you have can be different. But, the idea is same: use a given username to query whatever the system needs.

Method level security

Once finishing above settings, you can start using Winter Security to secure your program. Winter Security really emphasizes method level security. In a brief, you should have all your sensitive methods being registered to related permissions, and let the security framework check each method call to see if the required permission is granted to the caller/user who makes that call. In other words, all you need to do is to register a permission to each method. The way of doing that is to annotate the method with @PermissionCheck annotation.

Authenticate user

@PermissionCheck is an annotation defined by Winter Security. By barely placing this annotation on a method, the framework will do authentication check, and all authenticated users will be allowed to call the method.

Register method

To register a method, you just need to use this annotation on the method with a value, e.g. @PermissionCheck(“getAllUsers”) public Response getAll(){…}. The value “getAllUsers” is a permission name. It will be examed to match one of the permissions of the caller when the method is being called.

Non-protected method

If a method is not annotated with @PermissionCheck, it is not protected by Winter Security.

AuthenticationContext

One thing I would like to mention is the way to get caller’s information. Although, it is not implemented by Winter Framework, it is still good to know when using Winter Security.
Winter Security uses AuthenticationContext to store caller’s information of an incoming request, including name and password. Since Winter is built upon Java EE framework, it praises CDI to retreive AuthenticationContext. Thus, AuthenticationContext can be injected in any managed beans. In your code, simply make a field of @Inject AuthenticationContext, then you can get the caller’s name from it by calling getName() method.

Conclusion

After reading this blog, you should be able to setup and use Winter Security to secure your project. You may explore more about this framework when you atually use it in your project. If you really want to take a deeper look into Winter Project, you can check its GitHub repository. I hope you enjoy it.

* Because Winter Framework has not been submitted to Maven Central repository, the current version has to be installed to your local machine. However, when generating distributable .war file, you can choose to pack the dependencies to avoid dependency missing problems.
** AuthenticationContext is a class containing caller’s username and password of current request.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2lHwDmt
via IFTTT.

Overview of Winter Framework

Winter project is an open source project using Apache License
Version 2.0. It started in the Winter 2017, which was where its name came from.
Winter Framework intended to make life easier for Java Web Development with
Java EE environment. It helps developers to simplify common tasks such as
Security and Persistence in an efficient, easy, and best possible ways while
developing applications.

The roadmap of the Winter framework includes 5 major parts:
1. Winter Version Control: It can also be called Winter Parent,
which essentially a Maven POM project used as a parent project, which controls the
versions of dependencies that other Winter components use. It is important to
make sure each module uses the same versions of dependencies so that there is
no conflict between each other.
2. Winter Core: Winter uses CDI API (JSR 299: Contexts and
Dependency Injection for the JavaTM EE platform) as its default context and
dependency, which means it typically needs to run with an application server,
e.g. GlassFish, WildFly, etc. However, it has a light weight property file
injection component which is called Winter Core. Other Winter components depend
on it, and use it to inject properties and objects specified in the property
files.
3. Winter Security: Winter Security is the first up and running
component has been developed for people to use. The main difference between
Java EE security framework and Winter Security is the idea behind authorization
control. Java EE security framework primarily is a role based authorization
system. Methods or APIs are assigned to roles, and users who has the roles will
be authorized. There is nothing wrong about this mechanism, but it is not
natural. In other words, system does not know the workflows. It only knows when
to let pass or stop. Winter Security marks workflow on method level. Instead of
using configurational nor programmatical ways to control the authorization
process, developers can hand out the authorization to the business side, and
let whoever knows the business to take control of it.
4. Winter Data API: Winter Data API will be the next major
component to be developed per the roadmap. Inspired by Spring Data Framework, Winter
Data API will be similar but less complex. The target is to provide an easy to
use API which wraps JPA for developers to avoid boilerplate code for common
CRUD tasks.
5. Winter Common Utils: As in daily development, we always
have small utils that are necessary but does not come with standard libraries.
With Winter Core empowered, these utils now can be easier to use and
configurable.

So, if you are interested in this project, you can download
it on http://ift.tt/2k8v56X.
While I am writing this article, the current version of Winter Framework is 0.0.1-SNAPSHOT,
which means it is still under development. Even though, it is a fast-growing
project worth to give a try. Also, because it is open source, anyone can
download the code and contribute to it. This project is being managed as most
open source projects. To make your contributions, simply pick up an issue on its
GitHub repository and fix it, then make a pull request to submit your code. If
you find any bugs, you can also create an issue. If you know how to fix it, you
can fix it by yourself. Otherwise, leave the issue open to let other developers
fixing it.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2kprJK6
via IFTTT.

Develop AspectJ Library

AspectJ is an aspect-oriented programming (AOP) extension created at PARC for the Java programming language. – Wikipedia

In fact, things like Servlet Filters, EJB interceptors, or even database triggers are all sharing the concept of AOP. This article will focus on AspectJ in particular. Personally, I feel AspectJ gives a every different view on how software can be written. A weird thing that I found was most AspectJ related documentations were quite old. But, since it’s popular in many mordern frameworks such as Spring, I guess it’s worth to learn.

How is an AspectJ project used by other projects as a library?

To develop an AspectJ project and make other projects to use it, you have to know how the aspects are applied to the targeted components. AspectJ uses bytecode manipulation mechanism to intervene certain life cycle events of java classes at compile time. Because of that, it wouldn’t work if an AspectJ project is just being imported normally. Instead, it must be picked up at compile time to manipulate the bytecode when the targeted classes are generated. In fact, AspectJ has its own compiler, which could either be used standalone or work together with your chosen javac for jdk version control purposes.
To prepare for the practice in the rest sections, you need to have AspectJ Development Tools (AJDT) installed on your Eclipse. Although, I’ll introduce based on Eclipse, you can also develop AspectJ project with Intellij and NetBeans.

Eclipse plugin

AJDT is an eclipse plugin. You can find multiple versions of it. The latest one is 4.6 (copy the url as an Eclipse repository to install).

Intellij setup

You can find an introduction of how to set up your Intellij to work with AspectJ.

NetBeans plugin

There is a third party plugin called AspectJ-for-NetBeans developed quite a while ago (I heard it was developed by one person, which is very impresive).

Build an AspectJ project

There are various ways to create an AspectJ project: you can simply create an AspectJ project from scratch; you can have an existing Java project to convert to an AspectJ project. The way I’m going to do it is to create a Maven AspectJ project. By doing so, I would be able to just install my project to a local or remote repository. When it turns to that other project needs to import this AspectJ project, it can be done by just configuring the Maven configurations.

Create a Maven AspectJ project

A Maven AspectJ project is a maven project with a few AspectJ related configurations to assist while going through compile phase. Therefore, a simple Maven project is good to go for this practice.
Here is the initial pom.xml file I have (really nothing more than a simple initial pom file):
<project xmlns="http://ift.tt/IH78KX"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ca.ljz</groupId>
    <artifactId>special-logger</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</project>
By default, this project would not compile with AspectJ. To do that, we need to add:
  1. aspectj-maven-plugin
  2. aspectjrt (AspectJ run time dependency)
Optional: properties are optional. I added the above plugins and dependencies in <pluginManagement> and <dependencyManagement> first, which can be added to <plugins> and <dependencies> directly.
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.source-target.version>1.8</java.source-target.version>
    <aspectj.version>1.8.7</aspectj.version>
</properties>
<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>${java.source-target.version}</source>
                    <target>${java.source-target.version}</target>
                    <!-- IMPORTANT -->
                    <useIncrementalCompilation>false</useIncrementalCompilation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.7</version>
                <configuration>
                    <!-- OPTIONAL
                    <showWeaveInfo>true</showWeaveInfo>
                    -->
                    <source>${java.source-target.version}</source>
                    <target>${java.source-target.version}</target>
                    <Xlint>ignore</Xlint>
                    <complianceLevel>${java.source-target.version}</complianceLevel>
                    <encoding>${project.build.sourceEncoding}</encoding>
                    <!-- OPTIONAL
                    <verbose>true</verbose>
                    -->
                    <!-- OPTIONAL
                    <warn>
                        constructorName,
                        packageDefaultMethod,
                        deprecation,
                        maskedCatchBlocks,
                        unusedLocals,
                        unusedArguments,
                        unusedImport
                    </warn>
                    -->
                </configuration>
                <executions>
                    <execution>
                        <!-- IMPORTANT -->
                        <phase>process-sources</phase>
                        <goals>
                            <goal>compile</goal>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjtools</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
        </plugin>
        <!-- OPTIONAL
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
        </plugin>
        -->
    </plugins>
</build>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
    </dependency>
</dependencies>
The Maven AspectJ project now is created. As we mentioned above, the project needs to be compiled with either ajc (AspectJ compiler) or both ajc and javac. Please refer to the comments in the above pom settings to figure out how to do it in either way.

Create an annotation (optional)

Creating an annotation is not a must. But since it’s a common practice, I just want to show how to work with annotations in AspectJ. So, create an annotation first. It can be something like this:

package ca.ljz.annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(java.lang.annotation.ElementType.METHOD)
public @interface Log{
    String prefix() default "";
}

The purpose of this annotation is to let user place it on a specific method to log. It doesn’t sound like how most loggers work, but it’s good for this example.
Other than using an annotation, AspectJ can also catch a predefined signature pattern, e.g. a method signature pattern such as set* or get* etc. But, when programming a library, it’s very unlikely to use pattern matches in most case. The exceptions are setters and getters, etc.

Create an aspect

In AspectJ, an aspect is a special entity contains the descriptions of when and how to deal with life cycle events of targeted java classes. The following code stub describes a log aspect for what we are doing:

package ca.ljz.aspects;

import ca.ljz.annotations.Log;
import org.aspectj.lang.reflect.MethodSignature;

public aspect LogAspect {

    pointcut log() : execution(* *(..)) && @annotation(Log);

    before() : log() {
        System.out.println("enter "
            + ((MethodSignature) thisJoinPoint.getSignature()).
                getMethod().getAnnotation(Log.class).prefix()
            + thisJoinPoint.getSignature());
    }

    after() : log() {
        System.out.println("exit "
            + ((MethodSignature) thisJoinPoint.getSignature()).
                getMethod().getAnnotation(Log.class).prefix()
            + thisJoinPoint.getSignature());
    }
}
Here is a list of the meanings of each part of the pointcut declaration.

  • log(): the identifier of this pointcut, which can be referred in advices
  • execution: the action of the target to be intercepted
  • 1st *: this star indicate that the return type can be anything
  • 2nd *: this is the name pattern of methods, which in this case, means any name
  • (..): this refers to the parameter pattern, which in this case, means any parameter(s)
  • &&: this is an logic operator, which indicates both sides condition must satisfied
  • @annotation(Log): this means that there must be a Log annotation

before() and after() are the time points to indicate when the advice should be executed.
To know more about AspectJ syntax, here are some useful links:

Install the library

There are several types of places you can install your library. Just to keep things as simple as possible, I’m just going to run a built-in maven phase: install. You can easily find it by right click on the project, and it’s in Run As sub menu.

Import an AspectJ project

Like building an AspectJ project, to import an AspectJ project also requires to add/change to the AspectJ compiler. Depending on how you build your project, there are different ways to accomplish this.

Non-maven project

For a non-maven project, you need to:

  1. Convert the Java project to AspectJ project (right click project -> configure);
  2. Add the library into Project Build
  3. Add the library into AspectJ Build Inpath (project properties -> AspectJ Build);

Maven project

For a maven project, you need to:

  1. Configure the project into a Maven AspectJ project (see Create a Maven AspectJ project section);
  2. Add the library as a dependency;
  3. Add the library as an <aspectLibrary> into <configuration> in aspectj-maven-plugin
To add the library into aspectj-maven-plugin <configuration>, it needs to include <groupId> and <artifactId>. The aspect library is something like this:

<aspectLibraries>
    <aspectLibrary>
        <groupId>ca.ljz</groupId>
        <artifactId>special-logger</artifactId>
    </aspectLibrary>
</aspectLibraries>

In particular, to use this library, you just need to add @Log on any method. The project to import AspectJ library project can be either a jar or a war project.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2i8nNMm
via IFTTT.

Proxy Pattern Application

“In computer programming, the proxy pattern is a software design pattern. A proxy, in its most general form, is a class functioning as an interface to something else.” – Wikipedia
In other words, particularly in java programming language practice, you can use java.lang.reflect.Proxy class to construct instance of an interface.

When and why do you want to adopt Proxy pattern?

In a fashion of loosely coupled design, it is possible to get a set of interfaces without their concrete classes because there’s no multiple inheritance in java. If you want the entities to inherit from a base, there is no way of using concrete classes to bridge the persistence layer and presentation layer. To store and carry data to the persistence layer which is invisible to the presentation layer, you can either build another set of concrete classes or use proxy pattern. There are different concerns for both routes. I used the traditional one for my demo project looseCoupling branch. Whereas, for the EAR project assignment, I got the code following the proxy pattern.
From my study, I found if you want use MOXy, you can only parse XML. Other frameworks don’t support proxy pattern. Thus, if you need to use JSON, the traditional way is what you probably should go for.

A practice on Proxy pattern in parsing XML

In order to do XML binding with a proxy pattern. There are 3 steps to do it:

  1. Setup JAXBContextFactory;
  2. Build an ObjectFactory;
  3. Implement MessageBodyReader and MessageBodyWriter.

1. Setup JAXBContextFactory

To use MOXy, you need to add it into the project library. For maven, add the following to the pom.xml:
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.moxy</artifactId>
    <version>2.6.4</version>
</dependency>

Define javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory in jaxb.properties and place this file along with your Models or ObjectFactory.

Build an ObjectFactory

Before building the ObjectFactory class, you should have some interfaces like IUser to be manipulated against:

@javax.xml.bind.annotation.XmlRootElement
public interface IUser extends IModel {
    String getName();
    void setName(String name);
}

There are several ways to create an instance out of the interface, here is the route of using Proxy with an InvocationHandler. In this way, the instance to be generated will have a class signature something like this (example for IUser): public class Proxy$1 extends Proxy implements IUser. To implement the InvocationHandler interface, do the following:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
class InterfaceInvocationHandler implements InvocationHandler {
    private Map values = new HashMap();
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        if(methodName.startsWith("get"))
            return values.get(methodName.substring(3));
        else
            values.put(methodName.substring(3), args[0]);
        return null;
    }
}

This implementation basically performs/mocks getters and setters of the properties and stores the values in a HashMap.

import java.lang.reflect.Proxy;
@javax.xml.bind.annotation.XmlRegistry
public class ObjectFactory {
    public User createUser() {
        return createInstance(User.class);
    }
    private <T> T createInstance(Class<T> anInterface) {
        return (T) Proxy.newProxyInstance(anInterface.getClassLoader(), new Class[] {anInterface}, new InterfaceInvocationHandler());
    }
}

In the ObjectFactory, you can list as many models as you need. Although, they have to fit for your InterfaceInvocationHandler.

Implement MessageBodyReader and MessageBodyWriter

Based on my study, when building a REST service, there is no actual need for implementing the MessageBodyWriter because the out going message can retrieve data from the interface models. As long as you specified @Consumes(MediaType.APPLICATION_XML) annotation to ether the method or class level of your REST service, JAX-B will automatically perform marshaling for the models. However, you do need to implement the MessageBodyReader and let it help processing the in coming message.
As mentioned in above sections, since the Proxy class is the direct ancestor of the interface, you should let MessageBodyReader capture Proxy class (instead of doing it for each model classes) and do the parsing/unmarshaling before the message reach the certain REST method. It’s like an implicit interceptor to be enabled for the method once you annotate @Consumes(MediaType.APPLICATION_XML) on the REST service method or class.
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

@Provider
@Consumes({ MediaType.APPLICATION_XML, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class ProxyMessageBodyReader implements MessageBodyReader {
 @Override
 public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
  return type.getClass().isInstance(IModel.class);// the ancestor of IUser
 }
 @Override
 public Proxy readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
  try {
   JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
   final Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
   return (Proxy) unMarshaller.unmarshal(entityStream);
  } catch (final JAXBException ex) {
   LOG.error(ex.getMessage(), ex);
   throw new WebApplicationException(ex.getMessage(), Status.INTERNAL_SERVER_ERROR);
  }
 }
}

If you look closer to this code and the one in my assignment I linked to, you can see a slight difference on instantiating the JAXBContext. Unlike this one, it uses CDI. However, they are doing the same thing.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2g0OS3o
via IFTTT.

JAAS Setup Walkthrough

Few days ago, I was asked to write this article by my friend and classmate Ali Almutawakel. Thanks for this request, I got a lot of fun digging into JAAS.
JAAS stands for Java Authentication and Authorization Service, which is a JVM level security solution for Java applications. That means, in practice, it requires some setups with the platform to get it works. In this article, I will use WildFly as an example application server to demonstrate how it works. The source code that will be using in this article can be found on my github. There is a project I created few days ago called “demo“.

About the Demo Project

Regarding to this project, I want to thank my instructors, Aaron Warsylewicz, John O’Loughlin and Nicole Berard. They contributed their time to inspire me even though this project was not covered by my current program. Without them, I can’t start this article or get the project to work. In my opinion, JAAS by itself, is one of the toughest concept to understand. However, in this article, I’ll skip all the lower level details*, and directly jump into the practice.
To run this project, you need to download and import the source code to Eclipse, and run it on a WildFly application server along with a database (scripts for MySQL and Oracle are provided). You can download some tools to test against the RESTful Web Services, or you can just run the JUnit tests.
If you check my database script in the project, you will find 3 tables. They are a User table, a Group table, and a bridging table. This structure is very common and works well with JAAS. Notice that, although I have a persistence layer and all the entities, JAAS will not use them in this particular project with my settings.

Setting Steps

There are 3 steps to get JAAS working properly:

  1. configure the Application Server
  2. configure the project
  3. add annotations to your code (or you can do it in a programmatic way)

Configure the Application Server

To configure the security settings on WildFly in order to read credentials from database, you need to setup a data source for your database connection first. You can set all the configurations through the web console, or by changing the configuration file.
Web console solution:

  1. Login to WildFly web console (localhost:9990)
  2. Go to Configuration / Subsystem / Security
  3. Add a security domain. The name of the security domain will be used later in jboss-web.xml
  4. Open the security domain. Within the Authentication view, click Add to add an authentication module
  5. Click on Edit to edit the properties of this module (module option key value pairs).
Configuration File:
<security-domain name="demo" cache-type="default">
    <authentication>
        <login-module code="Database" flag="required">
            <module-option name="dsJndiName" value="java:/DemoDS" />
            <module-option name="principalsQuery"
                value="select password from demo_user where name=?" />
            <module-option name="rolesQuery"
                value="select g.name, 'Roles' from demo_user u, demo_group g, demo_user_group ug where u.name=? and u.id=ug.user_id and g.id=ug.group_id" />
            <module-option name="hashAlgorithm" value="SHA-256"/>
            <module-option name="hashEncoding" value="BASE64"/>
            <module-option name="ignorePasswordCase" value="true"/>
            <module-option name="hashStorePassword" value="false"/>
            <module-option name="hashUserPassword" value="true"/>
        </login-module>
    </authentication>
</security-domain>
There are few example security domains in the configuration file by default. So, it shouldn’t be difficult to find where to insert the above configuration. You can also check out my README.txt for configuring the application server.
This is the only section that really depends on the which application server you are using. However, most of them shares similar concepts. In addition, you can also create your own authentication mechanism, and setup in the application server.

Configure the Project

Project configurations for JAAS is pretty straight forward. However, knowing the limitations of it would be helpful when building your own applications. There are 2 files (for WildFly and JBoss) to be edited: web.xml and jboss-web.xml.

web.xml

In web.xml, there are 3 tags and their sub tags you need to manage in order to get JAAS configured within your project. Since you’ve configured the security domain in your application server, JAAS is already sitting there for you to use. So, you don’t have to configure the project to get the user principals. You can programmatically do the authentication and authorization with the user principals. In other words, you will be able to use annotations to automate the authentication and authorization processes.

<security-constraint>
This tag allows you to apply authentication process by specifying which web resource you want to constraint with what roles. A more general constraint will be overridden by the more specific constraints. For example: in the web.xml file of my project, the constraint “protected” will be applied to all urls with a pattern of /rest/*, except the put method for /rest/user/*, which is using the constraint “public”. In addition, if you don’t specify a role, then everyone can access.

<login-config>
Within this tag, you can config what method is used to do the authentication. BASIC can be a good choice for RESTful Web Services. However, since the password is not asked to be encrypted, you need SSL to encrypt the user credential. (SSL will not only encrypt the user credential but mostly everything, which is nice. But you need a dedicated IP to enable it. Check this article for details)


<security-role>
You can list all the roles (or I call “groups” in my project based on the database structure). These roles are used to associate with the authorizations by annotating them in your code. However, there are pros and cons for doing this. When there are a lot of changes with the security constraints or the security roles, hard configuring them is not a nice way that you want to go.

Personal experience
I had a project which the roles and constraints were constantly changing. For example, the accessibility of each level admin changed every few months, new roles were added, old roles were removed. In that case, since we didn’t predict this requirement, the web.xml configurations locked down all the roles and constraints, we lost the flexibility to change them within java code. To fix it (and meet the deadline), we actually made the program to rewrite the web.xml file. Because of that, every time the system applied new roles and constraints, the server had to restart to apply the changes. That was a disaster in my opinion. So, to know what the clients really need (not only what they say), and choose an appropriate approach is always critical to a complex system.

jboss-web.xml

jboss-web.xml is an JBoss/WildFly extension of web.xml file. If you see this file in my project, you’ll find it’s very straight forward, which only contains the name of the security domain.

Add Annotations

The Java security annotations are fairly simple. You add them to method level (code example) in different layers. It means, you don’t only take control of the security in your RESTful Web Services, but also the business logic layer or even persistent layer (code example).
There are 3 annotations being used mostly: javax.annotation.security.DeclareRoles, javax.annotation.security.PermitAll, javax.annotation.security.RolesAllowed. You can find them in the code examples.

Programmatic Approach

Unlike to apply annotations, you can do the authorization programmatically without configuring roles and constraints in web.xml file. To do that, you need to know if the caller is in a particular role, or you may also want to get caller principle from SessionContext.
* For more details about JAAS theory, there is an unpublished book JAAS in Action you can look into.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2ec1QOa
via IFTTT.

Build RESTful Web Services

REST is an end point to transfer data using XML or JSON. There are several advantages about REST Web Services you may want to look into.
To build RESTful Web Services, there are 4 major specifications to make:

  1. Path
  2. Media type
  3. Method type
  4. Path Parameter Injection
In addition, because REST takes paths mainly as parameters, it’s possible to nest paths from one to another.

1. Path

To make the service accessible, you need to give it an application path and sub paths. The application path can be specified in web.xml or through annotation:

web.xml

<servlet-mapping>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <url-pattern>/mainpath/*</url-pattern>
</servlet-mapping>

Annotation

@javax.ws.rs.ApplicationPath("mainpath")
public class MyStoreApplication extends javax.ws.rs.core.Application {
    /* empty class body */
}
For sub paths, @Path is placed on the class level. E.g. to reach the following class with above settings, the URL is http://<domain&gt;:<port>/<application_name>/mainpath/subpath
@Path("subpath")
public class Service{}

It is possible to put @Path on method level, and this will be talked in the following sections.

2. Media Type

There are mainly 2 types data that REST can produce or consume: XML and JSON. In particular, @Produces indicates the methods to send out responses with the XML or JSON data, whereas, @Consumes is for methods receiving XML or JSON data attached with requests. When they are annotated on the class level, it means the same as to annotate on every method within the class.

@Path("subpath")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Service{}

3. Method Type

Obviously, the RESTful Web Services should respond to different request accordingly. In order to do that, you can use @GET @POST @PUT @DELETE annotations on the methods to map with CRUD operations against database.

@Path("subpath")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Service{
    @GET
    public Response findById(String id){
        // ett can be a JSON String or the Entity object(s)
        return Response.status(Status.OK).entity(ett).build();
    }
}

4. Path Parameter Injection

In order to get the path parameter, which is a portion of the URL, @Path and @PathParam is used as following:

@Path("subpath")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Service{
    @EJB
    EntityEJB entityEJB;

    @GET
    @Path("{id}")
    public Response findById(@PathParam("id") String id){
        Entity ett = entityEJB.findById(id);
        return Response.status(Status.OK).entity(ett).build();
    }
}

In the above code, the braces surrounding id in @Path annotation indicates that id is a place holder in the URL. id in @PathParam means the value of this portion of URL is injected into the String id. For example, if the URL is .../subpath/a1-5, the value of String id will be “a1-5“.
In addition, the JSON object attached with the request can also be injected implicitly. Here is an example:

@PUT
public Object create(Entity ett) {
    return entityEJB.persist(ett);
}

Topic: nested path

There are cases you may want to organize methods of a Service in several classes. Check this code about Service and SubService to find more.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2eM5T4K
via IFTTT.

Send HTTP Request

When testing RESTful Web Services, you can’t just enter a URL in browser since that can only send a GET request. In order to conduct other request types, one way you can do is to use a ClientBuilder.

There are 3 steps to send a request using ClientBuilder:
  1. Create an Entity; (javax.ws.rs.client.Entity)
  2. Configure an Invocation$Builder;
  3. Use Invocation$Builder to send a request attached with the Entity.

Prerequisite

Because ClientBuilder itself is defined in javax.ws.rs.client, it needs a JavaEE container, or at least, the RESTEasy JAX-RS API, which I like to recommend.

Step 1. Create an Entity

The Entity creating here is mainly considered as a JSON or XML object wrapped by the Entity class, although you have many options. The following code shows how an Entity is conducted:

// Conduct an entity using content, which is an JSON String
Entity<String> entity = Entity.entity(content, MediaType.APPLICATION_JSON);

You can notice that the content is not necessarily to be a String, and the generic type of the entity is going to change accordingly.

Step 2. Configure an Invocation$Builder

To configure an Invocation$Builder, use ClientBuilder.newClient() to create a new Client object, configure the Client object, and build the Invocation$Builder:

  1. Create a new Client object;
  2. Configure the Client object;
  3. Build the Invocation$Builder.
// Create a new Client object
Client client = ClientBuilder.newClient();

// Set an authentication (if needed)
client = client.register(new BasicAuthentication(username, password));

// Set the url, which can be a String or wrapped object
WebTarget target = client.target(url);

// Build a builder
Builder builder = target.request();

Step 3. Use Invocation$Builder to send a request attached with the Entity.

Depending on what method you want to invoke on the server side, you can do GET, POST, PUT, DELETE, which generally are mapped to CRUD operations on the server side:

// To attach anything with GET method, modify the url
Response response = builder.get();

Response response = builder.post(entity);

Response response = builder.put(entity);

Response response = builder.delete(entity);

See another example of using the ClientBuilder in a demo project.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2eyHNu7
via IFTTT.