Sunday, 12 November 2017

Debugging web application with remote Tomcat



1. Right click on the project and go to Debug As -->Debug Configuration



2.On the opened window create a new Remote Java Application. Give a name to remote java application and go to Connect tab. Use default port 8000.






3. On the source tab select the scr folder of the project as shown below




4. update the start.bat file of the tomcat installation if using windows as shown below. Add jpda to the existing command




5. Set up the breakpoint in the java file as shown from where you want to start debugging



6. Start the tomcat server with below command



7. In eclipse start the debug mode as shown



8. Access the web application from browser and you will see eclipse light up in the bottom bar as shown. Control flow is stuck in the break point specified as in step 6 and you can start debugging from that point.



Tuesday, 22 August 2017

Securing webservice in spring boot framework


To add security infrastructure to a spring boot application below are the steps

Basic Security


1.In addition to the Spring boot starter, add spring security starter to the pom.

<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
      </dependency>

2. Write the Entry class for the Spring boot 

@SpringBootApplication
public class MyApplication {
        public static void main(String[] args){
        SpringApplication.run(MyApplication.class, args);
        }

}

3. Add a controller for the rest webservice 

 @RestController
       public class MySpringSecurityController {

           @RequestMapping(value="/login", method=RequestMethod.GET)
           public String login(){
 
            System.out.println("entry for my app..........");
            return "Success";
        }

Point 2 and 3 are required for setting up any spring booth application. When we add spring security starter in pom, this will add basic spring security infrastructure. If we now build and run the application we can see the basic authentication pop-up when we try to access any webservice endpoint.




Using username-password from database


We need two class for this to implement. 

1.   A configuration class that should extend WebSecurityConfigurerAdapter and use @EnableWebSecurity annotation


Following is achieved with this
1.1 Require the user to be authenticated prior to accessing any URL within our application
1.2 Enables HTTP Basic and Form based authentication
1.3 Spring Security will automatically render a login page and logout success page for you

  WebSecurityConfigurerAdapter: Provides a convenient base class for creating a WebSecurityConfigurer instance. The implementation allows customization by overriding methods.
  
   Important method that we may like to override are 

  1.1 ConfigureGlobal(AuthenticationManagerBuilder auth)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Autowired
     public void configureGlobal(AuthenticationManagerBuilder auth) 
       throws Exception {
         auth.inMemoryAuthentication().withUser("manas")
           .password("manas").roles("USER");
    }
                  }

      
Above method may be used to configure an user on memory. This can be used in simulation scenario.

        1.2 configure(HttpSecurity http)

 protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().fullyAuthenticated().and().
    httpBasic().and().
    csrf().disable();
}

This method cab be overridden for following
A.Form Login
B.Authorization with roles
C.Logout
D.HttpSecurity

2.   A class should extend GlobalAuthenticationConfigurerAdapter. 


GlobalAuthenticationConfigurerAdapter is a SecurityConfigurer that can be exposed as a bean to configure the global AuthenticationManagerBuilder using the init method.

@Configuration
public class NeeWebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter  {
public void init(AuthenticationManagerBuilder auth) throws Exception {
   auth.userDetailsService(userDetailsService());  
  }
}


AuthenticationManagerBuilder allows for easily building in memory authentication, LDAP authentication, JDBC based authentication, adding UserDetailsService, and adding AuthenticationProvider's.

UserDetailsService is a core interface which loads user-specific data.It is used throughout the framework as a user DAO and is the strategy used by the DaoAuthenticationProvider.
The interface requires only one read-only method, which simplifies support for new data-access strategies.
        @Bean
  UserDetailsService userDetailsService() {
    return new UserDetailsService() {

      public UserDetails loadUserByUsername(String username) throws  UsernameNotFoundException {
         Account account = accountRepository.findByUsername(username);
        if(account != null) {
        return new User(account.getUsername(), account.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER"));
        } else {
          throw new UsernameNotFoundException("could not find the user '"
                  + username + "'");
        }
      }
      
    };
  }

AuthenticationProvider: Spring Security provides a variety of options for performing authentication – all following a simple contract – an Authentication request is processed by an AuthenticationProvider and a fully authenticated object with full credentials is returned.



Github project implementing Spring Security



Resource

Thursday, 20 July 2017

Digital Signature and verification

Create Digital Signature

  1 Generate public-private key : 
Instantiate and initialize key-pair generator to generate keys
2. Digitally sign the file with private key:
Instantiate and initialize Signature to update the given file with signature generated

3. Persist the sign and public key:
      save the signed file and public key


public class CreateDigitalSignature {

public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, SignatureException, IOException {

// 1. Generate public-private key
Map<String, Key> keys = generateKeys();

// 2. Digitally sign the file with private key
byte[] sign = sign(keys.get("privateKey"));

// 3. Persist the sign and public key
saveSignAndPublicKey(keys.get("publicKey"), sign);

}

/**
 * The method generate public-private key.
 * This involved 3 steps, Instantiate, initialize and create
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
private static Map<String, Key> generateKeys() throws NoSuchAlgorithmException, NoSuchProviderException {

Map<String, Key> keys = new HashMap<>();

/**
 * Instantiate key-pair generator object using KeyPairGenerator
 * getInstance has two form: String algorithm  or provider(this guarantee that the implementation of an algorithm)
 */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");

/**
 * Keysize for a DSA key generator is the key length (in bits)
 * Instance of SecureRandom that uses the SHA1PRNG algorithm, as provided by the built-in SUN provide
 */
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
/**
 * Generate private & public key
 */
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();

keys.put("privateKey", privateKey);
keys.put("publicKey", publicKey);
System.out.println("Key is generated");

return keys;

}

/**
 * Method sign file with private key generated
 * @param key
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IOException
 */
private static byte[] sign(Key key) throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, SignatureException, IOException {

/**
 * Instantiate and initiate the Signature class
 */
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign((PrivateKey) key);
/**
 * Read in the data a buffer at a time and will supply it to the Signature object by calling the update method
 */
byte[] buffer = new byte[1024];
int len;
try (BufferedInputStream br = new BufferedInputStream(new FileInputStream("D:\\Demandware\\digitalSignature\\Name.txt"))) {

while ((len = br.read(buffer)) >= 0) {
dsa.update(buffer, 0, len);
}
}
/**
 * Generate the Signature
 */
byte[] realSig = dsa.sign();

return realSig;
}

/**
 * Method save the Signature and the Public Key in Files
 * @param key
 * @param signedFileInByte
 * @throws IOException
 */
private static void saveSignAndPublicKey(Key key, byte[] signedFileInByte) throws IOException {

/**
 * Save the sign in a file
 */
try (FileOutputStream savedSign = new FileOutputStream("D:\\Demandware\\digitalSignature\\mysign")) {

savedSign.write(signedFileInByte);
}

/**
 * Save the public key
 */
byte[] publickey = key.getEncoded();
try (FileOutputStream keyfos = new FileOutputStream("D:\\Demandware\\digitalSignature\\mypublickey")) {

keyfos.write(publickey);
}

}

}


Verification of digitally signed file

1. Get the public key
    Read the file used to store public key and store in an byte array. Using the keyStore get public              key

2. Get the signature
    Read the signature file and get the sign
3. Verify the file with public key and signature
     Open the requeted file and verify signature against signature

public class VerifySignature {

public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeySpecException, InvalidKeyException, SignatureException {

// Get the public key
PublicKey publickey = getPublicKey();

// get the signature
byte[] sign2Verify = getSignature2Verify();

// verify the file with public key and signature
verifySignature(publickey, sign2Verify);

}

/**
 * Generate the public key
 *
 * @return
 * @throws IOException
 * @throws FileNotFoundException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeySpecException
 */
private static PublicKey getPublicKey() throws IOException, FileNotFoundException, NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeySpecException {

/**
 * Read the file used to store public key and store in an byte array
 */
byte[] encKey = null;
try (FileInputStream keyFile = new FileInputStream("D:\\Demandware\\digitalSignature\\mypublickey")) {

encKey = new byte[keyFile.available()];
keyFile.read(encKey);
}

/**
 * Key specification required-assuming that the key was encoded
 * according to the X.509 standard-(built-in DSA key-pair generator
 * supplied by the SUN provider)
 */
X509EncodedKeySpec pubKeySpec = null;
if (encKey != null) {
pubKeySpec = new X509EncodedKeySpec(encKey);
}

/**
 * KeyFactory class in order to instantiate a DSA public key from its
 * encoding
 */
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");

/**
 * KeyFactory object to generate a PublicKey from the key specification
 */
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

return pubKey;
}

/**
 * Method return the signature after reading the file
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
private static byte[] getSignature2Verify() throws FileNotFoundException, IOException {

byte[] sign2Verify = null;
try (FileInputStream signFile = new FileInputStream("D:\\Demandware\\digitalSignature\\mysign")) {

sign2Verify = new byte[signFile.available()];
signFile.read(sign2Verify);
}

return sign2Verify;

}

/**
 * Method to verify signature
 * @param pubKey
 * @param sign2Verify
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IOException
 */
private static void verifySignature(PublicKey pubKey, byte[] sign2Verify) throws NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeyException, SignatureException, IOException {

/**
 *  Signature object that uses the same signature algorithm as was used to generate the signature
 */
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");

/**
 * initialize the Signature object
 */
sig.initVerify(pubKey);

/**
 * Read in the data a buffer at a time and will supply it to the
 * Signature object by calling the update method
 */
byte[] buffer = new byte[1024];
int len;
try (BufferedInputStream br = new BufferedInputStream(
new FileInputStream("D:\\Demandware\\digitalSignature\\Name.txt"))) {

while ((len = br.read(buffer)) >= 0) {
sig.update(buffer, 0, len);
}
}

/**
 * Verify the signature
 */
boolean verifies = sig.verify(sign2Verify);

System.out.println("signature verifies: " + verifies);

}

}

  
         

         



Streaming with Kafka API

The Kafka Streams API is a Java library for building real-time applications and microservices that efficiently process and analyze large-sca...