Step 1: Generate RSA key pair.
Here are the steps I took to create my RSA key pairs with Java keytoolcommand. Although I did this to configure my spring oauth2 jwt application, of course, it is not only restricted to that.
- Lets create our java keystore(.jks) file:
$ keytool -genkeypair -alias mytestkey -keyalg RSA \
-dname "CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US" \
-keypass changeme -keystore server.jks -storepass letmein
We generated a keypair named mytestkey with an RSA algorithm. Option -keypass changeme is to access the specific keypair, which is mytestkey in our case & -storepass letmein is to access the whole keystore file. -
Export public key certificate file.
$ keytool -export -keystore server.jks -alias mytestkey -file example.cer
With this certificate file we can find get our public key in the next section. - Using openssl to print the public key.
openssl x509 -inform der -in example.cer -pubkey -noout
This command will show the public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3Kd1vQNTLHLVhyMR0JHj
Q3CxJ9Roi6aZTzUk/HDerxJ+1ey8CdX4zf8bFA9Fh21KTojw87yt76A6GpCuru6P
zxCou0GLPwFwKCS1SFcsysOMSxRAhgIssjujGnbC2Q0XPDpsGYJVavnHGZ7cI7Hn
sXqHcL0dmbgEfI7NR7wCGHoo1NxjfwOQXtCGH3w/Tg2BLA3HNyRclrCfJuS3aj0y
tr7tOWdzgguztH6E4xoqKdn7FEMMtBEsggw7Z4H8uziUy37Z7iOMTdmwZvbpMrns
IUZElqnYcRFYLPRH5xsSl1Y129fAbW03WW63agzy9DWO5HhT44ePJDrkZqsEaHKw
/QIDAQAB
-----END PUBLIC KEY-----
Another way to achieve this using java code, which is bit more complex, is:
1
2
3
4
|
KeyPair keyPair =
new
KeyStoreKeyFactory(
new
ClassPathResource(
"server.jks"
),
"letmein"
.toCharArray())
.getKeyPair(
"mytestkey"
,
"changeme"
.toCharArray());
System.out.println(
new
String(Base64.encode(keyPair.getPublic().getEncoded())));
|
This code was inspired by spring oauth2
s JwtAccessTokenConverter
.
Step 2: Configure Spring Oauth2
- Authorization server:.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Configuration
@EnableAuthorizationServer
protected
static
class
OAuth2Config
extends
AuthorizationServerConfigurerAdapter {
//other configurations are omitted.
@Bean
public
JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter =
new
JwtAccessTokenConverter();
KeyPair keyPair =
new
KeyStoreKeyFactory(
new
ClassPathResource(
"server.jks"
),
"letmein"
.toCharArray())
.getKeyPair(
"mytestkey"
,
"changeme"
.toCharArray());
converter.setKeyPair(keyPair);
return
converter;
}
}
|
- Resource Server:
In yourapplication.yml
file(note that spacing is messed up below, you should have a proper spacing):
spring:
oauth2:
resource:
jwt:
keyValue: |
—–BEGIN PUBLIC KEY—–
MIIBIjANBgkqhkiG9…
—–END PUBLIC KEY—–