【Spring Security Oauth2】构建授权服务器(三):使用数据库存储客户端信息

一、环境准备

1、回顾

【Spring Security Oauth2】构建授权服务器(一):内存模式

2、Sql脚本

create database d_study_oauth2 character set utf8;
use d_study_oauth2;

-- auto-generated definition
create table oauth_client_details
(
    client_id               varchar(255)                        not null comment '客户端标 识'
        primary key,
    resource_ids            varchar(255)                        null comment '接入资源列表',
    client_secret           varchar(255)                        null comment '客户端秘钥',
    scope                   varchar(255)                        null,
    authorized_grant_types  varchar(255)                        null,
    web_server_redirect_uri varchar(255)                        null,
    authorities             varchar(255)                        null,
    access_token_validity   int                                 null,
    refresh_token_validity  int                                 null,
    additional_information  longtext                            null,
    create_time             timestamp default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP,
    archived                tinyint                             null,
    trusted                 tinyint                             null,
    autoapprove             varchar(255)                        null
)
    comment '接入客户端信息';

-- auto-generated definition
create table oauth_code
(
    create_time    timestamp default CURRENT_TIMESTAMP not null,
    code           varchar(255)                        null,
    authentication blob                                null
);

create index code_index
    on oauth_code (code);

3、application.yml配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/d_study_oauth2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: root

二、构建授权服务器(三):使用数据库存储客户端信息

1、Pom依赖 ,需引入DataSource数据源。

1.1、Jdbc数据源

		<!-- mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

1.2、Mybatis-Plus

		<!-- mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
		<!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

2、改造AuthorizationServer类

2.1、新增代码

	@Autowired private DataSource dataSource;

    /**
     * 客户端配置,取数据库数据
     * @return
     */
    @Bean
    public ClientDetailsService jdbcClientDetailsService() {
        JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        clientDetailsService.setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }

2.2、改造authorizationCodeServices()方法,将授权码生成后保存在数据库中

	@Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        // 设置授权码模式的授权码存取在数据库中
        return new JdbcAuthorizationCodeServices(dataSource);

        //设置授权码模式的授权码如何 存取,暂时采用内存方式
        // return new InMemoryAuthorizationCodeServices();
    }

2.3、改造configure(ClientDetailsServiceConfigurer clients)方法

/**
     * 配置客户端详细信息
     * TODO 将来改成在数据库中
     *
     * @param clients
     * @throws Exception
     */
    @SuppressWarnings("All")
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // JDBC存储
        clients.withClientDetails(jdbcClientDetailsService());

        // // in‐memory存储
        // clients.inMemory()
        //         // 客户端标识
        //         .withClient("c1")
        //         // 客户端秘钥
        //         .secret(passwordEncoder.encode("secret"))
        //         // 资源列表
        //         .resourceIds("res1")
        //         // 允许授权的五种类型
        //         .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
        //         // 允许的授权范围
        //         .scopes("all")
        //         // false=跳转到授权页面,true=直接方法令牌
        //         .autoApprove(false)
        //         // 加上验证回调地址
        //         .redirectUris("http://www.baidu.com");
    }

2.4、改造tokenService()令牌服务方法,获取数据库中的过期时间、token刷新时间等配置

/**
     * 令牌服务
     *
     * @return
     */
    @SuppressWarnings({"All"})
    @Bean
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices service = new DefaultTokenServices();
        // TODO 作用
        // 客户端信息服务
        service.setClientDetailsService(jdbcClientDetailsService());
        // 是否刷新令牌
        service.setSupportRefreshToken(true);
        // 令牌存储策略
        service.setTokenStore(tokenStore);
        // // 令牌默认有效期2小时
        // service.setAccessTokenValiditySeconds(7200);
        // // 刷新令牌默认有效期3天
        // service.setRefreshTokenValiditySeconds(259200);

        // 加入JWT配置
        // TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        // tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        // service.setTokenEnhancer(tokenEnhancerChain);
        return service;

3、问题总结

1、DataSource依赖注入报错

在这里插入图片描述
原因:未引入DataSource数据源的依赖,引入依赖即可。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值