Bootstrap

基于Spring Boot2 + Spring Security OAuth2 实现单点登陆(二)

放几个阿里云的优惠链接 代金券 / 高性能服务器2折起 / 高性能服务器5折

关于单点登陆的基本实现:点这里

实现一个基于jdbc的OAuth2认证

本文主要介绍使用jdbc存储token的例子。代码基于上一篇文章做一些修改实现。
源码地址


修改项目依赖
project("sso-auth-server") {
    dependencies {
        compile 'org.springframework.boot:spring-boot-starter-web'
        compile 'org.springframework.boot:spring-boot-starter-security'
        compile 'org.springframework.boot:spring-boot-starter-jdbc' // 新添加
        compile 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.0.0.RELEASE'
        runtime 'mysql:mysql-connector-java' // 新添加
    }
}

创建OAuth2数据存储相关表

Spring官方给出了基于HSQL建表sql。本文数据库使用mysql,对它做了一些修改。看这里

  • 配置数据库链接
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://127.0.0.1:3306/oauth2test
  • 创建数据库表
    这里直接使用程序调用sql脚本实现。
public class AuthenticationApplication {
    private static final Logger log = LoggerFactory.getLogger(AuthenticationApplication.class);

    public static void main(String[] args) throws SQLException {
        initDatabase();
        new SpringApplicationBuilder(AuthenticationApplication.class)
                .run(args);
    }

    public static void initDatabase() throws SQLException {
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.setSqlScriptEncoding("utf-8");
        populator.addScript(new DefaultResourceLoader().getResource("schema.sql"));
        populator.populate(DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306", "root", "123456"));
        log.info("database init complete");
    }
}


配置AuthorizationServerConfigurer实现类
  • 修改配置
public class Oauth2Config extends AuthorizationServerConfigurerAdapter implements ApplicationRunner {
    ...省略重复代码
    @Autowired
    private DataSource dataSource;
    // 使用JdbcTokenStore把token存储到数据库中,RedisTokenStore的使用方法也类似
    @Bean
    public TokenStore jdbcTokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 设置OAuth2的client信息也使用数据库存储和读取
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager).tokenStore(jdbcTokenStore());
    }
    ...
}
  • 添加测试数据
    实现ApplicationRunner(spring boot 启动时会调用这个接口),添加数据
@Override
    public void run(ApplicationArguments args) throws Exception {
        // 给测试环境添加预置的client
        JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        clientDetailsService.setPasswordEncoder(passwordEncoder);
        try {
            clientDetailsService.loadClientByClientId("testclient");
        } catch (ClientRegistrationException e) {
            BaseClientDetails details = new BaseClientDetails();
            details.setClientId("testclient");
            details.setClientSecret("testclient");
            details.setScope(Arrays.asList("test", "test2"));
            details.setAutoApproveScopes(Arrays.asList("test"));
            details.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "refresh_token"));
            clientDetailsService.addClientDetails(details);
        }
        log.info("add default client complete");
    }

测试方法与上一篇介绍相同
;