JSON web token (JWT) implementation in Java

In my previous article , I talked about JWT introduction and how it works. There are multiple libraries by which you can implement JWT in Java.

1. Java JWT: JSON Web Token for Java and Android

Installation

Use your favorite Maven-compatible build tool to pull the dependency (and its transitive dependencies) from Maven Central:

Maven:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.6.0</version>
</dependency>



Gradle:


dependencies {
    compile 'io.jsonwebtoken:jjwt:0.6.0'
}

Note: JJWT depends on Jackson 2.x. If you’re already using an older version of Jackson in your app, read this

Usage

Most complexity is hidden behind a convenient and readable builder-based fluent interface, great for relying on IDE auto-completion to write code quickly. Here’s an example:

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;
import java.security.Key;

// We need a signing key, so we'll create one just for this example. Usually
// the key would be read from your application configuration instead.
Key key = MacProvider.generateKey();

String s = Jwts.builder().setSubject("Joe").signWith(SignatureAlgorithm.HS512, key).compact();
How easy was that!?

Now let's verify the JWT (you should always discard JWTs that don't match an expected signature):

assert Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody().getSubject().equals("Joe");
You have to love one-line code snippets!

But what if signature validation failed? You can catch SignatureException and react accordingly:

try {

    Jwts.parser().setSigningKey(key).parseClaimsJws(compactJwt);

    //OK, we can trust this JWT

} catch (SignatureException e) {

    //don't trust the JWT!
}

2. Using Nimbus Jose + JWT

The most popular and robust Java library for JSON Web Tokens (JWT)
Supports all standard signature (JWS) and encryption (JWE) algorithms
Open source Apache 2.0 licence

Features –

– Signed / encrypted tokens, such as bearer access tokens in OAuth 2.0 or OpenID Connect identity tokens;
– Self-contained API keys, with optional revocation;
– Protecting content and messages;
– Authenticating clients and web API requests.

Use in Java

// Create an HMAC-protected JWS object with some payload
JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256),
                                    new Payload("Hello world!"));

// We need a 256-bit key for HS256 which must be pre-shared
byte[] sharedKey = new byte[32];
new SecureRandom().nextBytes(sharedKey);

// Apply the HMAC to the JWS object
jwsObject.sign(new MACSigner(sharedKey));

// Output to URL-safe format
jwsObject.serialize(); 

Maven configuration

Maven
For Java 7+ :

<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>4.11.2</version>
</dependency>

3. JSON token library – It depend on Google Guava.The library is in fact used by Google Wallet.

Here is how to create a jwt, and to verify it and deserialize it:

Maven –

<dependency>
    <groupId>com.googlecode.jsontoken</groupId>
    <artifactId>jsontoken</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

and Java implementation –

import java.security.InvalidKeyException;
import java.security.SignatureException;
import java.util.Calendar;
import java.util.List;

import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.JsonTokenParser;
import net.oauth.jsontoken.crypto.HmacSHA256Signer;
import net.oauth.jsontoken.crypto.HmacSHA256Verifier;
import net.oauth.jsontoken.crypto.SignatureAlgorithm;
import net.oauth.jsontoken.crypto.Verifier;
import net.oauth.jsontoken.discovery.VerifierProvider;
import net.oauth.jsontoken.discovery.VerifierProviders;

import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;

import com.google.common.collect.Lists;
import com.google.gson.JsonObject;


/**
 * Provides static methods for creating and verifying access tokens and such. 
 * @author davidm
 *
 */
public class AuthHelper {

    private static final String AUDIENCE = "NotReallyImportant";

    private static final String ISSUER = "YourCompanyOrAppNameHere";

    private static final String SIGNING_KEY = "[email protected]^($%*$%";

    /**
     * Creates a json web token which is a digitally signed token that contains a payload (e.g. userId to identify 
     * the user). The signing key is secret. That ensures that the token is authentic and has not been modified.
     * Using a jwt eliminates the need to store authentication session information in a database.
     * @param userId
     * @param durationDays
     * @return
     */
    public static String createJsonWebToken(String userId, Long durationDays)    {
        //Current time and signing algorithm
        Calendar cal = Calendar.getInstance();
        HmacSHA256Signer signer;
        try {
            signer = new HmacSHA256Signer(ISSUER, null, SIGNING_KEY.getBytes());
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }

        //Configure JSON token
        JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
        token.setAudience(AUDIENCE);
        token.setIssuedAt(new org.joda.time.Instant(cal.getTimeInMillis()));
        token.setExpiration(new org.joda.time.Instant(cal.getTimeInMillis() + 1000L * 60L * 60L * 24L * durationDays));

        //Configure request object, which provides information of the item
        JsonObject request = new JsonObject();
        request.addProperty("userId", userId);

        JsonObject payload = token.getPayloadAsJsonObject();
        payload.add("info", request);

        try {
            return token.serializeAndSign();
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Verifies a json web token's validity and extracts the user id and other information from it. 
     * @param token
     * @return
     * @throws SignatureException
     * @throws InvalidKeyException
     */
    public static TokenInfo verifyToken(String token)  
    {
        try {
            final Verifier hmacVerifier = new HmacSHA256Verifier(SIGNING_KEY.getBytes());

            VerifierProvider hmacLocator = new VerifierProvider() {

                @Override
                public List<Verifier> findVerifier(String id, String key){
                    return Lists.newArrayList(hmacVerifier);
                }
            };
            VerifierProviders locators = new VerifierProviders();
            locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);
            net.oauth.jsontoken.Checker checker = new net.oauth.jsontoken.Checker(){

                @Override
                public void check(JsonObject payload) throws SignatureException {
                    // don't throw - allow anything
                }

            };
            //Ignore Audience does not mean that the Signature is ignored
            JsonTokenParser parser = new JsonTokenParser(locators,
                    checker);
            JsonToken jt;
            try {
                jt = parser.verifyAndDeserialize(token);
            } catch (SignatureException e) {
                throw new RuntimeException(e);
            }
            JsonObject payload = jt.getPayloadAsJsonObject();
            TokenInfo t = new TokenInfo();
            String issuer = payload.getAsJsonPrimitive("iss").getAsString();
            String userIdString =  payload.getAsJsonObject("info").getAsJsonPrimitive("userId").getAsString();
            if (issuer.equals(ISSUER) && !StringUtils.isBlank(userIdString))
            {
                t.setUserId(new ObjectId(userIdString));
                t.setIssued(new DateTime(payload.getAsJsonPrimitive("iat").getAsLong()));
                t.setExpires(new DateTime(payload.getAsJsonPrimitive("exp").getAsLong()));
                return t;
            }
            else
            {
                return null;
            }
        } catch (InvalidKeyException e1) {
            throw new RuntimeException(e1);
        }
    }


}

public class TokenInfo {
    private ObjectId userId;
    private DateTime issued;
    private DateTime expires;
    public ObjectId getUserId() {
        return userId;
    }
    public void setUserId(ObjectId userId) {
        this.userId = userId;
    }
    public DateTime getIssued() {
        return issued;
    }
    public void setIssued(DateTime issued) {
        this.issued = issued;
    }
    public DateTime getExpires() {
        return expires;
    }
    public void setExpires(DateTime expires) {
        this.expires = expires;
    }
}

Happy API secure using JWT with Vinay

Reference
– https://github.com/jwtk/jjwt
– http://connect2id.com/products/nimbus-jose-jwt
– https://code.google.com/archive/p/jsontoken/

WebCenter Portal 11g Certification

Hi All,

Another exam , i gave now Oracle Webcenter 11g essential exam that mean IZ0-541.I somehow , managed to pass.So ,now i am now Oracle Webcenter portal 11g certified implementation specialist. 🙂

Tips for new candidates – Its bit tricky and confusing too.I found one question have all options are wrong. weird isn’t it? All options are wrong,
focus on Webcenter spaces,content , how to add different portal using which protocol and so on.few question on ADF too.Passing percentage 65%.Time to complete exam is 120 mintues The questions were confusing.

Read more: https://www.techartifact.com/blogs/2013/11/oracle-adf-certification.html#ixzz2mh3dbuz0

Prepration material –
Webcenter 11g administration cookbook – http://www.packtpub.com/oracle-webcenter-11g-ps3-administration-cookbook/book
Oracle webcenter 11g handbook . – http://www.amazon.com/Oracle-WebCenter-11g-Handbook-Customizable/dp/0071629327

Learn Hibernate core implementation.- How hibernate works

Lessons to learn from the Hibernate Core implementation

Hibernate is an open source Java persistence framework project. Perform powerful object relational mapping and query databases using HQL and SQL.
In general the widely used libraries are well designed and implemented, and it’s very interesting to learn from them some coding best practices. Let’s take a look inside the hibernate core library and discover some of its design keys.
In this post Hibernate Core is analyzed by JArchitect to go deep inside its design and implementation.

Package by Feature
Package-by-feature uses packages to reflect the feature set. It places all items related to a single feature (and only that feature) into a single directory/package. This results in packages with high cohesion and high modularity, and with minimal coupling between packages. Items that work closely together are placed next to each other.
Here’s a good article talking about packaging by feature.
Hibernate core contains many packages, each one is related to a specific feature hql, sql, and others.

Coupling
Low coupling is desirable because a change in one area of an application will require fewer changes throughout the entire application. In the long run, this could alleviate a lot of time, effort, and cost associated with modifying and adding new features to an application.
Here are three key benefits derived from using interfaces:
• An interface provides a way to define a contract that promotes reuse. If an object implements an interface then that object is to conform to a standard. An object that uses another object is called a consumer. An interface is a contract between an object and its consumer.
• An interface also provides a level of abstraction that makes programs easier to understand. Interfaces allow developers to start talking about the general way that code behaves without having to get in to a lot of detailed specifics.
• An interface enforce low coupling between components, what’s make easy to protect the interface consumer from any implementation changes in the classes implementing the interfaces.
Let’s search for all interfaces defined by Hibernate Core, for that we use CQLinq to query the code base.

from  t in Types where t.IsInterface select t

If our primary goal is to enforce low coupling, there’s a common mistake when using interfaces that could kill the utility of using them. It’s the using of the concrete classes instead of interfaces, and to explain better this problem let’s take the following example:
The class A implements the Interface IA who contains the calculate() method, the consumer class C is implemented like that

public class C

{

   ….

   public void calculate()

   {

     …..

     m_a.calculate();

     ….

    }

    A m_a;

}

The Class C instead of referencing the interface IA, it references the class A, in this case we lose the low coupling benefit, and this implementation has two major drawbacks:
• If we decide to use another implementation of IA, we must change the code of C class.
• If some methods are added to A not existing in IA, and C use them, we also lose the contract benefit of using interfaces.
C# introduced the explicit interface implementation capability to the language to ensure that a method from the IA will be never called from a reference to concrete classes, but only from a reference to the interface. This technique is very useful to protect developers from losing the benefit of using interfaces.
With JArchitect we can check this kind of mistakes using CQLinq, the idea is to search for all methods from concrete classes used directly by other methods.

from m in Methods  where m.NbMethodsCallingMe>0 && m.ParentType.IsClass

 && !m.ParentType.IsThirdParty && !m.ParentType.IsAbstract

let interfaces= m.ParentType.InterfacesImplemented

from i in interfaces where i.Methods.Where(a=>a.Name==m.Name &&

a.ParentType!=m.ParentType).Count()>0 

select new { m,m.ParentType,i }

For example the method getEntityPersister from SessionFactoryImpl which implements SessionFactoryImplementor interface is concerned by this problem.
Let’s search for methods invoking directly SessionFactoryImpl.getEntityPersister.
from m in Methods where m.IsUsing (“org.hibernate.internal.SessionFactoryImpl.getEntityPersister(String)”)
select new { m, m.NbBCInstructions }

Methods like SessionImpl.instantiate invoke directly getEntityPersister, instead of passing by interface, what break the benefit of using interfaces. Fortunately hibernate core doesn’t contains many methods having this problem.
Coupling with external jars
When external libs are used, it’s better to check if we can easily change a third party lib by another one without impacting the whole application, there are many reasons that can encourage us to change a third party lib. The other lib could:
– Have more features.
– More powerful.
– More secure.
Let’s take the example of antlr lib which used to parse the hql queries, and imagine that another parser more powerful than antlr was created, could we change the antlr by the new parser easily?
To answer this question let’s search which methods from hibernate use it directly:

from m in Methods where m.IsUsing ("antlr-2.7.7")
select new { m, m.NbBCInstructions }
 

And which ones used it indirectly:

from m in Projects.WithNameNotIn( "antlr-2.7.7").ChildMethods()
let depth0 = m.DepthOfIsUsing("antlr-2.7.7")
where depth0 > 1 orderby depth0
select new { m, depth0 }

Many methods use antlr directly what makes hibernate core highly coupled with it, and changing antlr with another one is not an easy task. this fact not means that we have a problem in hibernate design, but we have to be careful when using a third party lib and well check if a third party lib must be low coupled or not with the application.
Cohesion
The single responsibility principle states that a class should have one, and only one, reason to change. Such a class is said to be cohesive. A high LCOM value generally pinpoints a poorly cohesive class. There are several LCOM metrics. The LCOM takes its values in the range [0-1]. The LCOMHS (HS stands for Henderson-Sellers) takes its values in the range [0-2]. Note that the LCOMHS metric is often considered as more efficient to detect non-cohesive types.
LCOMHS value higher than 1 should be considered alarming.
In general classes more concerned by the cohesion are the classes having many methods and fields.
Let’s search for types having many methods and fields.

from t in Types where
(t.Methods.Count() > 40 || t.Fields.Count()>40) && t.IsClass
orderby t.Methods.Count() descending
select new { t, t.InstanceMethods, t.Fields,t.LCOMHS }

Only few types are concerned by this query, and for all them the LCOMHS is less than 1.
Using Annotations
Annotation-based development relieves Java developers from the pain of cumbersome configuration. And give us a powerful feature to free the source code from the boilerplate code. The resulting code is also less likely to contain bugs.
Let’s search for all annotations defined by hibernate core.
from t in Types where t.IsAnnotationClass && !t.IsThirdParty select t

Many annotations are defined, what make hibernate easy to use by developers, and the headache of configuration files is avoided.
Conclusion
Hibernate Core is a good example of open source projects to learn from, don’t hesitate to take a look inside it.