Monday, August 15, 2016

JAVA REST Client


 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 import java.io.OutputStream;  
 import java.net.HttpURLConnection;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 /**  
  * Created by jasintha on 8/4/16.  
  */  
 public class RestClient {  
   public static void main(String[] args) {  
     try {  
       URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");  
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
       conn.setDoOutput(true);  
       conn.setRequestMethod("POST");  
       conn.setRequestProperty("Content-Type", "application/json");  
       String input = "{\"qty\":100,\"name\":\"iPad 4\"}";  
       OutputStream os = conn.getOutputStream();  
       os.write(input.getBytes());  
       os.flush();  
       if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {  
         throw new RuntimeException("Failed : HTTP error code : "  
             + conn.getResponseCode());  
       }  
       BufferedReader br = new BufferedReader(new InputStreamReader(  
           (conn.getInputStream())));  
       String output;  
       System.out.println("Output from Server .... \n");  
       while ((output = br.readLine()) != null) {  
         System.out.println(output);  
       }  
       conn.disconnect();  
     } catch (MalformedURLException e) {  
       e.printStackTrace();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
   }  
 }  

Convert SMAL response to JWT

Here I have used opensaml and WSO2 rg.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil clazz to process this request



 package org.wso2.is.jwt.inbound.authenticator.servlets;  
 import io.jsonwebtoken.JwtBuilder;  
 import io.jsonwebtoken.Jwts;  
 import io.jsonwebtoken.SignatureAlgorithm;  
 import org.apache.velocity.runtime.directive.Foreach;  
 import org.opensaml.saml2.core.Assertion;  
 import org.opensaml.saml2.core.Attribute;  
 import org.opensaml.saml2.core.AttributeStatement;  
 import org.opensaml.xml.XMLObject;  
 import org.w3c.dom.Element;  
 import org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean;  
 import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;  
 import javax.crypto.spec.SecretKeySpec;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import java.io.IOException;  
 import javax.xml.bind.DatatypeConverter;  
 import org.opensaml.saml2.core.Response;  
 import org.wso2.is.jwt.inbound.authenticator.util.Constants;  
 import java.security.Key;  
 import java.util.Date;  
 import java.util.HashMap;  
 import java.util.List;  
 import java.util.Map;  
 public class JWTServlet extends HttpServlet {  
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
     response.setContentType("text/html");  
     String[] samlResponses = request.getParameterMap().get(Constants.SAML_RESPONSE);  
    if(samlResponses!=null){  
      try {  
        LoggedInSessionBean sessionBean = new LoggedInSessionBean();  
        sessionBean.setSAML2SSO(sessionBean.new SAML2SSO());  
        String saml2ResponseString = SAMLSSOUtil.decodeForPost(samlResponses[0]);  
        Response saml2Response = (Response) SAMLSSOUtil.unmarshall(saml2ResponseString);  
        sessionBean.getSAML2SSO().setResponseString(saml2ResponseString);  
        sessionBean.getSAML2SSO().setSAMLResponse(saml2Response);  
        List<Assertion> assertions = saml2Response.getAssertions();  
        Assertion assertion = null;  
        String subject = null;  
        if (assertions != null && !assertions.isEmpty()) {  
          assertion = assertions.get(0);  
        }  
        if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {  
          subject = assertion.getSubject().getNameID().getValue();  
        }  
        final Map<String, Object> attributeMap = getAssertionStatements(assertion);  
        String idPEntityIdValue = assertion.getIssuer().getValue();  
        String url = assertion.getConditions().getAudienceRestrictions().get(0).getAudiences().get(0).getAudienceURI();  
        String id = saml2Response.getID();  
        String jwtString = createJWT(id, idPEntityIdValue, subject,attributeMap,1000*60*3);  
        response.sendRedirect(url+ Constants.QUERY_PARAM +jwtString);  
      }catch (Exception e){  
         /*ignore*/  
      }  
    }  
   }  
   private Map<String, Object> getAssertionStatements(Assertion assertion) {  
     Map<String, Object> results = new HashMap<String, Object>();  
     if (assertion != null && assertion.getAttributeStatements() != null) {  
       List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();  
       for (AttributeStatement statement : attributeStatementList) {  
         List<Attribute> attributesList = statement.getAttributes();  
         for (Attribute attribute : attributesList) {  
           Element value = attribute.getAttributeValues().get(0).getDOM();  
           Object attributeValue = value.getTextContent();  
           results.put(attribute.getName(), attributeValue);  
         }  
       }  
     }  
     return results;  
   }  
 private String createJWT(String id, String issuer, String subject,Map<String,Object> claims,int ttlMillis) {  
     SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;  
     long nowMillis = System.currentTimeMillis();  
     Date now = new Date(nowMillis);  
     byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Constants.KEY_SCRET);  
     Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());  
     JwtBuilder builder = Jwts.builder().setId(id)  
         .setIssuedAt(now)  
         .setSubject(subject)  
         .setIssuer(issuer)  
         .signWith(signatureAlgorithm, signingKey);  
     builder.setClaims(claims);  
     if (ttlMillis >= 0) {  
     long expMillis = nowMillis + ttlMillis;  
     Date exp = new Date(expMillis);  
     builder.setExpiration(exp);  
     }  
   return builder.compact();  
   }  
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
     doGet(request, response);  
   }  
 }  



Create & Processing JWT in JAVA

I am using JJWT library to process the JWT 


 package org.wso2.is.jwt.inbound.authaticator;  
 import io.jsonwebtoken.Claims;  
 import io.jsonwebtoken.JwtBuilder;  
 import io.jsonwebtoken.Jwts;  
 import io.jsonwebtoken.SignatureAlgorithm;  
 import org.wso2.is.jwt.inbound.authenticator.util.Constants;  
 import javax.crypto.spec.SecretKeySpec;  
 import javax.servlet.http.HttpSession;  
 import javax.xml.bind.DatatypeConverter;  
 import java.security.Key;  
 import java.util.Date;  
 import java.util.HashMap;  
 import java.util.Map;  
 public class JWTRespondMessagTest {  
   public static void main(String[] args) {  
     try {  
       JWTRespondMessagTest messagTest = new JWTRespondMessagTest();  
       Map<String, Object> results = new HashMap<String, Object>();  
       results.put("org.wso2.is/mobile", "0711368118");  
       String jwtString = messagTest.createJWT("id","idp","jasinth@wso2",results,1000*60*5);  
       messagTest.readJWT(jwtString);  
     }catch (Exception e){  
     }  
   }  
   private String createJWT(String id, String issuer, String subject,Map<String,Object> claims,int ttlMillis) {  
     SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;  
     long nowMillis = System.currentTimeMillis();  
     Date now = new Date(nowMillis);  
     byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("wso2carbon");  
     Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());  
     //Let's set the JWT Claims  
     JwtBuilder builder = Jwts.builder().setId(id)  
         .setIssuedAt(now)  
         .setSubject(subject)  
         .setIssuer(issuer)  
         .signWith(signatureAlgorithm, signingKey);  
     builder.setClaims(claims);  
     if (ttlMillis >= 0) {  
       long expMillis = nowMillis + ttlMillis;  
       Date exp = new Date(expMillis);  
       builder.setExpiration(exp);  
     }  
     return builder.compact();  
   }  
   public void readJWT(String jwt){  
     String claimedId = "Annonimus";  
     String subjectId = "Annonimus";  
     if (jwt == null) {  
     } else {  
       try{  
       Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary("wso2carbon")).parseClaimsJws(jwt).getBody();  
       if(claims!=null){  
         subjectId = claims.getSubject();  
         String val =(String) claims.get("org.wso2.is/mobile");  
         System.out.println(val);  
         System.out.println(subjectId);  
       }  
     }catch (Exception e){  
        e.printStackTrace();  
       }  
     }  
   }  
 }