Deploy to Application Container Cloud Service from Oracle Storage Cloud via REST API

As mentioned in my previous post about Application container cloud. We can use two options to upload application archive to ACSS

  • UI console (Already covered in previous post)
  • From Stroge cloud service via REST API

In this post, we will talk about upload archive via storage cloud Service using REST API. There is two steps for that

  1. Store archive to Storage Cloud service.
  2. Deploy Archive to ACCS.

tttttt

Information credentials for cloud account should be handy as identity, domain, password for using in REST API. Using cURL scripts to upload your application to the storage service.

 

Note :  cURL is a tool to transfer data from or to a server, using one of the supported protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP.

 

Store archive to Storage Cloud service

 

Before uploading in Storage cloud, We need to build container in Storage Cloud Service. Either you can via Storage cloud UI console. Building using UI console is pretty easy and straightforward.

 



 

We will create container via curl command.

  1. Below Script will create storage container.    
# CREATE STORAGE CONTAINER
curl -i -X PUT \ -u User-Name:Password \ https://hostname/v1/Storage-Identity-Domain/App-Name

 

  1. Now upload your application archive to the storage container.
# PUT ARCHIVE IN STORAGE CONTAINER
curl -i -X PUT \-u User-Name:Password \ https://hostname/v1/Storage-Identity-Domain/App-Name/Archive-File-Name -T Path-to-local-file/Archive-File-Name

For example use following script to upload it

curl -i -X PUT \ -u sampleUserName:samplePassword \ https://storage.oraclecloud.com/v1/Storagecontainer/DeveloperSkillsApp/SpringBootJpaDev-1.0-dist.zip -T target/SpringBootJpaDev-1.0-dist.zip

After running these script, it is uploaded to Storage cloud container.

 


 

Deploy Archive to ACCS –

After uploading archive to Storage cloud servicee, ACC’s deployment procedure can be invoked. We need to provide standard set of information while deploying. Sample schema of script should be as follows

# Mock Deployment Script
url -i -X POST  \
  -u User-Name:Password \
  -H "X-ID-TENANT-NAME:Identity-Domain" \
  -H "Content-Type: multipart/form-data" \
  -F "name=App-Name" \
  -F "runtime=java" \
  -F "subscription=Monthly" \
  -F "[email protected]" \
  -F "archiveURL=App-name/Archive-File-Name" \
  -F "notes=Your Notes here" \
  https://hostname/paas/service/apaas/api/v1.1/apps/Identity-Domain

Trying to upload with following script –

curl -v -u "USERNAME:PASSWORD” -X POST -H "X-ID-TENANT-NAME: IDENTITY_DOMAIN" -H "Content-Type: multipart/form-data" -F "name=Developer-skills-service" -F "runtime=java" -F "subscription=Monthly" -F "archiveURL= Storagecontainer/SpringBootJpaDev-1.0-dist.zip " -F "notes=Developer Skills Service Deployment" https://apaas.REGION.oraclecloud.com/paas/service/apaas/api/v1.1/apps/IDENTITY_DOMAIN

 

When you deploy your application, you can reference a deployment.json file. Information about deployment like memory , instances etc. can be pass via deployment.json.

 

You can automate these two process using maven. You can also configured this by maven plugin in Oracle Developer cloud services.

 

 

That’s all for now. Happy Oracle Cloud learning.

Build Secure Application Using JSON Web Tokens (JWT)

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

Below picture will give more better explanation

The claims in a JWT are encoded as a JSON object that is base64url encoded and consists of zero or more name/value pairs (or members), where the names are strings and the values are arbitrary JSON values. Each member is a claim represented by the JWT.

What JWT contains – JWT consists of three main components: a header object, payload object, and a signature. These three properties are encoded using base64, then concatenated with periods as separators.

for example

xxxxxxxxxxxxxxxxxx.yyyy.zzzzzzzzzzzzzzzzzzzzzzzzz

xxxxxxxxxxxxxxxxxxxxx – header
yyyy – – claims/payload
zzzzzzzzzzzzzzzzzzzz – signature

Header: The header contains the metadata for the token and at a minimal contains the type of the signature and/or encryption algorithm
Claims: The claims contains any information that you want signed
JSON Web Signature (JWS): The headers and claims digitally signed using the algorithm in the specified in the headerStructure of a JWT

JSON Web Token example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwuY29tI iwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluI jp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0.yRQYnWzskCZUxPwaQupWk iUzKELZ49eM7oWxAQK_ZXw

Since there are 3 parts separated by a ., each section is created differently. We have the 3 parts which are:

header
payload
signature
..

Header

The JWT Header declares that the encoded object is a JSON Web Token (JWT) and the JWT is a JWS that is MACed using the HMAC SHA-256 algorithm. For example:

{
“alg”: “HS256”,
“typ”: “JWT”
}
“alg” is a string and specifies the algorithm used to sign the token.

“typ” is a string for the token, defaulted to “JWT”. Specifies that this is a JWT token.

Payload (Claims)

A claim or a payload can be defined as a statement about an entity that contians security information as well as additional meta data about the token itself.

Following are the claim attributes :

iss: The issuer of the token

sub: The subject of the token

aud: The audience of the token

qsh: query string hash

exp: Token expiration time defined in Unix time

nbf: “Not before” time that identifies the time before which the JWT must not be accepted for processing

iat: “Issued at” time, in Unix time, at which the token was issued

jti: JWT ID claim provides a unique identifier for the JWT

Signature

JSON Web Signatre specification are followed to generate the final signed token. JWT Header, the encoded claim are combined, and an encryption algorithm, such as HMAC SHA-256 is applied. The signatures’s secret key is held by the server so it will be able to verify existing tokens.

JWT-Real world

Advantages of Token Based Approach

JWT approach allows us to make AJAX calls to any server or domain. Since the HTTP header is used to transmit the user information.

Their is no need for having a separate session store on the server. JWT itself conveys the entire information.

Server Side reduces to just an API and static assets(HTML, CSS, JS) can be served via a CDN.

The authentication system is mobile ready, the token can be generated on any device.

Since we have eliminated the need for cookies, we no more need to protect against the cross site requesets.

API Keys provide either-or solution, whereas JWT provide much granular control, which can be inspected for any debugging purpose.

API Keys depend on a central storage and a service. JWT can be self-issued or an external service can issue it with allowed scopes and expiration.

You can use jwt in node.js, angular.js, ruby, Java, .net and other frameworks.
Following is example of JWT generator and verify jwt token

Generate Tokens

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import io.jsonwebtoken.*;
import java.util.Date;    

//Sample method to construct a JWT

private String createJWT(String id, String issuer, String subject, long ttlMillis) {

//The JWT signature algorithm we will be using to sign the token
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);

//We will sign our JWT with our ApiKey secret
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
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);

 //if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
    long expMillis = nowMillis + ttlMillis;
    Date exp = new Date(expMillis);
    builder.setExpiration(exp);
}

 //Builds the JWT and serializes it to a compact, URL-safe string
return builder.compact();
}

Decode and Verify Tokens

import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;

//Sample method to validate and read the JWT
private void parseJWT(String jwt) {
//This line will throw an exception if it is not a signed JWS (as expected)
Claims claims = Jwts.parser()         
   .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
   .parseClaimsJws(jwt).getBody();
System.out.println("ID: " + claims.getId());
System.out.println("Subject: " + claims.getSubject());
System.out.println("Issuer: " + claims.getIssuer());
System.out.println("Expiration: " + claims.getExpiration());
}

Happy secure API call with Vinay in techartifact . 🙂

– See more at:
http://blog.apcelent.com/json-web-token-tutorial-example-python.html#sthash.GzZriR3U.dpuf
http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/

How to Create and verify JWTs in Java

RESTFul Service example using Apache CXF and Spring

In recent times there is lot of growth in RESTFul services. I thought it would be nice to talk about it.

This example is using Apache CXF and Spring. There are some other frameworks e.g Jersey (Reference Sun implementation), RestEasy, the JBoss choice and Apache CXF.

Here is bacic web configuration adding Spring context and CXF tranport servlet.

  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/services.xml</param-value>
    </context-param>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

There is Cities service using Spring annotations, this has been configured using Spring annotation
Second annottatiions is of CXF to define the mount point REST service

@Service("timeService")
@Path("cities")
public class CitiesListingService {

    @GET
    @Produces({"application/json", "application/xml"})
    public RestFulCities getCities() {
        List<City> cities = new LinkedList<City>();
        cities.add(new City("New Delhi", "011", "19M"));
        cities.add(new City("Mumbai", "022", "21M"));
        cities.add(new City("Chennai", "044", "10M"));
        RestFulCities restFulCities = new RestFulCities();
        restFulCities.setRestFulCityList(getCities(cities));
        return restFulCities;
    }

Here is Spring configuration for connection cxf and spring beans together.

<context:component-scan base-package="com.techartifact.example.spring"/>

    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>

    <jaxrs:server id="restContainer" address="/">
        <jaxrs:serviceBeans>
            <ref bean="timeService"/>
        </jaxrs:serviceBeans>
        <jaxrs:extensionMappings>
            <entry key="json" value="application/json"/>
            <entry key="xml" value="application/xml"/>
        </jaxrs:extensionMappings>
        <jaxrs:providers>
            <ref bean="jaxbXmlProvider"/>
        </jaxrs:providers>
    </jaxrs:server>

    <!-- Webservice message handlers -->
    <bean id="jaxbXmlProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
        <property name="jaxbElementClassNames" ref="elements"/>
    </bean>

    <util:list id="elements">
        <value>com.techartifact.example.spring.model.RestFulCity</value>
        <value>com.techartifact.example.spring.model.RestFulCities</value>
    </util:list>

Yes that’s it. Now build the code and run it.

Run example

Download full example code from here spring-RESTapplication

Go to project directory [spring-RESTapplication] in command shell and run following command using maven

mvn clean package
mvn -Pcargo-run

http://localhost:8080/springrest/rest/cities

CXF can also produces output in json format, use following url to see out put in json

http://localhost:8080/springrest/rest/cities.json