Integrating JWT with Spring Security OAuth2 Provider

OAuth2 is an authentication framework and JWT (JSON Web Tokens) is an authentication protocol.

Related articles:
Spring Security OAuth2 Provider Minimum Implementation
Spring Security OAuth2 Provider Database Storage
Spring Security OAuth2 Provider Third-Party Login Simple Demonstration
Spring Security OAuth2 Provider Custom Development
Spring Security OAuth2 Provider

Integration

JWT Resource Server needs to add dependencies.

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-jwt</artifactId>
    <optional>true</optional>
</dependency>


(2) Generate a signed certificate

to generate a certificate
quote
# keytool -genkeypair -alias jwt-test -keyalg RSA -dname "CN=jwt,OU=ren,O=ren,L=china,S=china,C=CN" -keypass my_pass -keystore jwt-test.jks -storepass my_pass

Put the .jks file in the Authorization Server's src/main/resources/jwt-test.jks

to export the public key
quote
# keytool -list -rfc --keystore jwt-test.jks | openssl x509 -inform pem -pubkey

Copy the PUBLIC KEY part to src/main/resources/public.txt of Resource Server

(3) Authentication server settings

@Bean
protected JwtAccessTokenConverter jwtTokenEnhancer() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt-test.jks"), "my_pass".toCharArray());
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt-test"));
    return converter;
}

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}


(4) Resource server settings

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    Resource resource = new ClassPathResource("public.txt");
    String publicKey = null;
    try {
        publicKey = IOUtils.toString(resource.getInputStream());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    converter.setVerifierKey(publicKey);
    return converter;
}

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}


(5) Confirmation test

to obtain Token:


Confirm Token through jwt.io:


Access resource API through access_token:


(6) Algorithm HS256
changes the configuration of Authorization Server and Resource Server to:
@Bean
protected JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey("rensanning");
    return converter;
}


Get Token:


Confirm Token through jwt.io:


Access resource API through access_token:


Reference:
http://www.baeldung.com/spring-security-oauth-jwt
https://github.com/dynamind/spring-boot-security -oauth2-minimal

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326242028&siteId=291194637