Configuring Spring Oauth2 with JWT & asymmetric RSA keypair

来源:互联网 发布:js修改input边框颜色 编辑:程序博客网 时间:2024/06/07 04:09

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.

  1. 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.

  2. 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.

  3. 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 = newKeyStoreKeyFactory(
    newClassPathResource("server.jks"),"letmein".toCharArray())
    .getKeyPair("mytestkey","changeme".toCharArray());
System.out.println(newString(Base64.encode(keyPair.getPublic().getEncoded())));

This code was inspired by spring oauth2JwtAccessTokenConverter.

Step 2: Configure Spring Oauth2

  1. Authorization server:.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableAuthorizationServer
protectedstatic class OAuth2Config extendsAuthorizationServerConfigurerAdapter {
//other configurations are omitted.
@Bean
publicJwtAccessTokenConverter jwtAccessTokenConverter() {
    JwtAccessTokenConverter converter = newJwtAccessTokenConverter();
    KeyPair keyPair = newKeyStoreKeyFactory(
           newClassPathResource("server.jks"),"letmein".toCharArray())
        .getKeyPair("mytestkey","changeme".toCharArray());
    converter.setKeyPair(keyPair);
    returnconverter;
}
 
}
  1. Resource Server:
    In your application.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—–

原创粉丝点击