web-dev-qa-db-fra.com

Quelles sont les étapes pour implémenter le Token Store de Spring en tant que fichier MySQL?

J'ai une application qui utilise actuellement Spring OAuth 2.0 In Memory Token Store. J'ai besoin de convertir le fichier JAR Spring Security OAuth 2.0 pour utiliser un fichier persistant plutôt qu'un fichier en mémoire afin de garantir la validité des jetons d'accès lors du redémarrage du serveur. Le JAR Spring OAuth 2.0 fournit des routines pour prendre en charge une base de données MYSQL à l'aide de la méthode JdbcTokenStore, mais je suis incapable de trouver une documentation indiquant comment changer la configuration par défaut (qui utilise la méthode InMemoryTokenStore) pour utiliser la méthode Jdbc prise en charge.

J'aimerais avoir des nouvelles de quelqu'un qui a implémenté la méthode Spring Security OAuth 2.0 JdbcTokenStore et qui peut soit fournir un exemple de la configuration requise pour le faire, soit me diriger vers une documentation décrivant le processus. J'ai cherché haut et bas sur Internet, mais je ne trouve aucune documentation de ce type.

J'ai déjà trouvé le fichier de schéma Spring Security OAuth 2.0 pour le magasin de jetons, qui, s'il est intéressé, ne figure que dans le répertoire des ressources de test. Sa présence n'est documentée par aucun des sites Web de documentation Pivotal. Si nécessaire, je peux lire le reste du code source Pivotal, mais j'espère que quelqu'un pourra me sauver de l'obligation d'utiliser ce chemin.

Merci d'avance pour toute aide que vous pouvez fournir.

16
Donald F. Coffin

Vous devez modifier la classe d'implémentation des beans d'InMemoryTokenStore en JdbcTokenStore. Et avec cette modification, vous devrez également passer une source de données dans le constructeur.

J'ai déjà fait cela en rigolant avec ça. Vous pouvez le trouver ici

et la configuration de sécurité du printemps change spécifiquement ici . Le schéma MySql est ici

22
anfab

Voici comment je l'ai fait.

Étape 1: Créez 2 tables (oauth_access_token et oauth_refresh_token)

CREATE TABLE `oauth_access_token` (
`authentication_id` varchar(255) NOT NULL,
`token_id` varchar(255) NOT NULL,
`token` blob NOT NULL,
`user_name` varchar(255) NOT NULL,
`client_id` varchar(255) NOT NULL,
`authentication` blob NOT NULL,
`refresh_token` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `oauth_access_token`
ADD PRIMARY KEY (`authentication_id`);


CREATE TABLE `oauth_refresh_token` (
`token_id` varchar(255) NOT NULL,
`token` blob NOT NULL,
`authentication` blob NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Étape 2: Configurez la classe AuthorizationServerConfig

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private TokenStore tokenStore;

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore);
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory().withClient("my-trusted-client")
            .authorizedGrantTypes("client_credentials", "password","refresh_token")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT").scopes("read", "write", "trust")
            .resourceIds("oauth2-resource")
            .accessTokenValiditySeconds(5000)
            .refreshTokenValiditySeconds(50000)
            .secret(passwordEncoder.encode("secret"));
}

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.checkTokenAccess("isAuthenticated()");
}

}

Étape 3: 

@Configuration
public class AppConfig {

@Value("${spring.datasource.url}")
private String datasourceUrl;

@Value("${spring.datasource.driver-class-name}")
private String dbDriverClassName;

@Value("${spring.datasource.username}")
private String dbUsername;

@Value("${spring.datasource.password}")
private String dbPassword;

@Bean
public DataSource dataSource() {
    final DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(dbDriverClassName);
    dataSource.setUrl(datasourceUrl);
    dataSource.setUsername(dbUsername);
    dataSource.setPassword(dbPassword);
    return dataSource;
}

@Bean
public TokenStore tokenStore() {
    return new JdbcTokenStore(dataSource());
}
}
2
VK321