Sunday, 23 September 2018

JWT Json Web Token Claims - Token Creation and Parsing Example : using jjwt-0.2.jar

Basic - Json Webtoken Example




       

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.TextCodec;

public class JwtTokenUtil {

 public static void main(String[] args) throws UnsupportedEncodingException {

  System.out.println(createAccessJwtToken());

 }

 public static String createAccessJwtToken() throws UnsupportedEncodingException {

  Claims claims = Jwts.claims().setSubject("sanal");
  claims.put("role", "admin,super");
  claims.put("registered", 1);
  claims.put("firstName", "sanal");
  claims.put("lastName", "samuel");

  LocalDateTime currentTime = LocalDateTime.now();

  String token = Jwts.builder().setClaims(claims).setIssuer("OFV")
    .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
    .signWith(SignatureAlgorithm.HS512,
      TextCodec.BASE64.decode("Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E="))
    .compact();

  parser(token);

  return token;
 }

 public static void parser(String jwt) throws UnsupportedEncodingException {
  Jws jws = Jwts.parser()
    .setSigningKey(TextCodec.BASE64.decode("Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E="))
    .parseClaimsJws(jwt);
  System.out.println(jws.getBody());

  Claims claims = jws.getBody();
  System.out.println(claims.getSubject());

 }

}


       
 

Rest Endpoint Invocation over SSL (HTTPS) - Using Spring RestTemplate , Certificate Keystore , SSLContext , SocketFactory JKS


Main Class to achieve rest invocation to any url over HTTPS.
Pre requisite:- Make sure the certificate is imported into new JKS keystore.
The certificate should be added to cacert of your JDK .
       

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author Sanal 
Invoking a Rest Endpoint over SSL
 */
public class RestInvoker {

 // resttemplate has its own encoding mechanism - so do not try encoded urls
 static String restURL = "https://google.com";

 public static void main(String[] args)

 {

  try {
   System.out.println("Invoking Rest Client");

   HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

   SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(SSLFactory.getSSLContext());
   CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
   requestFactory.setHttpClient(httpClient);
   RestTemplate restTemplate = new RestTemplate();

   restTemplate.setRequestFactory(requestFactory);

   System.out.println("INVOKING " + restURL);

   ResponseEntity response = restTemplate.getForEntity(restURL, String.class);
   System.out.println("Response Status Code  " + response.getStatusCodeValue());
   System.out.println("Response Body  " + response.getBody());
  } catch (Exception e) {
   System.out.println("Rest Invocation failed " + e.getStackTrace());
  }

 }

 /*
  * Static Class that will invoke the SSLContext with the appropriate Certs
  * used for the HttpClient Request
  */

 public static class SSLFactory {

  private static String jksFilePath = "C:/Users/Desktop/certs.jks";
  private static String jksPwd = "password";
  private static KeyStore ks;
  private static SSLContext sslContext;

  public SSLFactory() {

   System.out.println("Get a Socket Factory Loaded with Custom certs");

  }

  public static SSLContext getSSLContext() {
   try {

    sslContext = SSLContexts.custom().loadKeyMaterial(loadKeyStore(), jksPwd.toCharArray()).build();
   } catch (Exception e) {
    System.out.println(" KeyStore getSSLContext Exception" + e.getStackTrace());
   }
   return sslContext;

  }

  public static KeyStore loadKeyStore() {
   try (InputStream in = new FileInputStream(new File(jksFilePath))) {
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    System.out.println("KEYSTORE INIT");

    ks.load(in, jksPwd.toCharArray());

   } catch (Exception e) {
    System.out.println(" Loading KeyStore Exception" + e.getStackTrace());
   }
   return ks;

  }

 }

}


       
 

AWS Certificate Manager - Import Certificate

How to import a certificate. Use Key Store Explorer to open the cert and export keypair in PEM format  This will save a file cert.pem. Make ...