Saturday, August 27, 2016

Keystore and Public Key Generation for Spring OAuth2 JWT


If you are going to implement Gateway Pattern (involving an Auth Server, UI Server and Resource Server) using Spring Boot OAuth2, you may want to look on to the sample at Github. The sample clearly illustrates how to implement the pattern. But, if you want to create your own Keystore and Public Key, the following instruction will be useful.

The instructions are taken from http://www.baeldung.com/spring-security-oauth-jwt. First, execute the following command:

keytool -genkeypair -alias myalias -keyalg RSA -keystore mykeystore.jks 

Enter keystore password:  
Re-enter new password: 
What is your first and last name?
  [Unknown]:  Juan Dela Cruz
What is the name of your organizational unit?
  [Unknown]:  My Company
What is the name of your organization?
  [Unknown]:  My Organization
What is the name of your City or Locality?
  [Unknown]:  Antipolo
What is the name of your State or Province?
  [Unknown]:  Rizal
What is the two-letter country code for this unit?
  [Unknown]:  PH
Is CN=Juan Dela Cruz, OU=My Company, O=My Organization, L=Antipolo, ST=Rizal, C=PH correct?
  [no]:  yes

Enter key password for <myalias>
(RETURN if same as keystore password):

The command will produce mykeystore.jks file. Then, we export the public key through Java:

    public static void main(String[] args) {
        KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource("keystore.jks"), "10qpalzm".toCharArray())
                .getKeyPair("safesatcentral", "10qpalzm".toCharArray());
        System.out.println(new String(Base64.encode(keyPair.getPublic().getEncoded())));
    }

After all of these, you may now apply your custom Keystore and Public Key to your Spring OAuth2 project using JWT.