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

本文介绍如何使用JDBC存储OAuth2的token,并通过示例代码展示了如何配置Spring Security OAuth2来实现这一目标。文章包括了创建必要的数据库表、配置数据源以及初始化测试数据等步骤。

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

实现一个基于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");
    }
复制代码

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

转载于:https://juejin.im/post/5adc8d94f265da0b7d0af6f6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值