栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring-cloud整合oauth2.0

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring-cloud整合oauth2.0

文章目录

介绍

分为4种模式

授权模式密码模式简化模式客户端模式 搭建简单模式(使用内存的参数)

授权模式

导入pom配置application.yml配置授权服务器配置资源服务器配置 spring security编写controller编写service编写启动类测试

1.获取授权码2.通过授权码获取token3.通过token获取用户信息 密码模式

修改配置 spring security修改配置授权服务器测试

1.通过账号,密码获取token2.通过token获取信息 刷新令牌

修改配置授权服务器服务器测试

1.使用密码模式获取刷新的token2.通过刷新token获取一个新的token 搭配JWT使用

导入pom编写Jwt配置类修改配置授权服务器测试

1.通过密码模式获取token2.通过加密后的token获取用户信息 sso 搭建(使用数据库的参数)

另外导入3个包修改授权服务器修改application.yml配置文件测试

介绍
分为4种模式

授权模式 密码模式 简化模式 客户端模式

搭建简单模式(使用内存的参数)
授权模式

导入pom
        
            org.springframework.cloud
            spring-cloud-starter-oauth2
        
配置application.yml
server:
  port: 7787
spring:
  main:
    #允许我们自己覆盖spring放入到IOC容器的对象
    allow-bean-definition-overriding: true
  application:
    name: oauth-server
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
配置授权服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置client_id
                .withClient("client")
                //配置client‐secret
                .secret(passwordEncoder.encode("123123"))
                //配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                //配置刷新token的有效期
                .refreshTokenValiditySeconds(864000)
                //配置redirect_uri,用于授权成功后跳转
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all")
                //配置grant_type,表示授权类型
                .authorizedGrantTypes("authorization_code");
    }
}
配置资源服务器
@Configuration
@EnableResourceServer
public class ResourceServiceConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                // 受保护的资源
                .and().requestMatchers().antMatchers("/user
@Configuration
public class JwtTokenStoreConfig {

    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
        //配置JWT使用的秘钥
        accessTokenConverter.setSigningKey("123123");
        return accessTokenConverter;
    }
}
修改配置授权服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    UserService userService;

    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private AuthenticationManager authenticationManagerBean;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManagerBean) // 使用密码模式必须配置
                .tokenStore(tokenStore)//配置存储令牌策略
                .accessTokenConverter(jwtAccessTokenConverter)//使用jwt
                .reuseRefreshTokens(false)//refresh_tokens是否重复使用
                .userDetailsService(userService)//刷新令牌授权是否包含对用户信息的检查
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);//支持get和post请求
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单认证
        security.allowFormAuthenticationForClients();
    }
    
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        
        clients.inMemory()
                //配置client_id
                .withClient("client")
                //配置client‐secret
                .secret(passwordEncoder.encode("123123"))
                //配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                //配置刷新token的有效期
                .refreshTokenValiditySeconds(864000)
                //配置redirect_uri,用于授权成功后跳转
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all")
                //配置grant_type,表示授权类型
                
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "refresh_token");
    }
}
测试 1.通过密码模式获取token

访问:http://localhost:7787/oauth/token?username=fox&password=123456&grant_type=password&client_id=client&client_secret=123123&scope=all

得到加密后的token

2.通过加密后的token获取用户信息

访问:http://localhost:7787/user/getCurrentUser?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDc0MjA3MTEsInVzZXJfbmFtZSI6ImZveCIsImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6Ijc3MDI3YmJkLWI3OGUtNDFjYy05ODk1LTMyODVjZGJkNjZiYSIsImNsaWVudF9pZCI6ImNsaWVudCIsInNjb3BlIjpbImFsbCJdfQ.yZtRfAdkH5VsPFM5kPjX2pMdjQZYzjqgP6u-xbM2IyA

得到用户数据

成功!!!

sso 搭建(使用数据库的参数)

SQL脚本

CREATE TABLE `tb_permission`
(
    `id`          BIGINT(20)   NOT NULL AUTO_INCREMENT,
    `parent_id`   BIGINT(20)   DEFAULT NULL COMMENT '父权限',
    `name`        VARCHAR(64)  NOT NULL COMMENT '权限名称',
    `enname`      VARCHAR(64)  NOT NULL COMMENT '权限英文名称',
    `url`         VARCHAR(255) NOT NULL COMMENT '授权路径',
    `description` VARCHAR(200) DEFAULT NULL COMMENT '备注',
    `created`     DATETIME     NOT NULL,
    `updated`     DATETIME     NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 44
  DEFAULT CHARSET = utf8 COMMENT ='权限表';
INSERT INTO `tb_permission`(`id`, `parent_id`, `name`, `enname`, `url`, `description`, `created`,
                            `updated`)
VALUES (39, 38, '查询订单', 'orderView', '/order/selectOrderInfoByIdAndUsername', NULL,
        '2019-04-04 15:30:30', '2019-04-04 15:30:43'),
       (45, 44, '查询商品', 'productView', '/product/selectProductInfoById', NULL,
        '2019-04-06 23:49:39', '2019-04-06 23:49:41');


CREATE TABLE `tb_role`
(
    `id`          BIGINT(20)  NOT NULL AUTO_INCREMENT,
    `parent_id`   BIGINT(20)   DEFAULT NULL COMMENT '父角色',
    `name`        VARCHAR(64) NOT NULL COMMENT '角色名称',
    `enname`      VARCHAR(64) NOT NULL COMMENT '角色英文名称',
    `description` VARCHAR(200) DEFAULT NULL COMMENT '备注',
    `created`     DATETIME    NOT NULL,
    `updated`     DATETIME    NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 38
  DEFAULT CHARSET = utf8 COMMENT ='角色表';
INSERT INTO `tb_role`(`id`, `parent_id`, `name`, `enname`, `description`, `created`, `updated`)
VALUES (37, 0, '超级管理员', 'admin', NULL, '2019-04-04 23:22:03', '2019-04-04 23:22:05');

CREATE TABLE `tb_role_permission`
(
    `id`            BIGINT(20) NOT NULL AUTO_INCREMENT,
    `role_id`       BIGINT(20) NOT NULL COMMENT '角色 ID',
    `permission_id` BIGINT(20) NOT NULL COMMENT '权限 ID',
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 43
  DEFAULT CHARSET = utf8 COMMENT ='角色权限表';
INSERT INTO `tb_role_permission`(`id`, `role_id`, `permission_id`)
VALUES (37, 37, 37),
       (38, 37, 38),
       (39, 37, 39),
       (40, 37, 40),
       (41, 37, 41),
       (42, 37, 42),
       (43, 37, 44),
       (44, 37, 45),
       (45, 37, 46),
       (46, 37, 47),
       (47, 37, 48);

CREATE TABLE `tb_user`
(
    `id`       BIGINT(20)  NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(50) NOT NULL COMMENT '用户名',
    `password` VARCHAR(64) NOT NULL COMMENT '密码,加密存储',
    `phone`    VARCHAR(20) DEFAULT NULL COMMENT '注册手机号',
    `email`    VARCHAR(50) DEFAULT NULL COMMENT '注册邮箱',
    `created`  DATETIME    NOT NULL,
    `updated`  DATETIME    NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `username` (`username`) USING BTREE,
    UNIQUE KEY `phone` (`phone`) USING BTREE,
    UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE = InnoDB
  AUTO_INCREMENT = 38
  DEFAULT CHARSET = utf8 COMMENT ='用户表';
INSERT INTO `tb_user`(`id`, `username`, `password`, `phone`, `email`, `created`, `updated`)
VALUES (37, 'fox', '$2a$10$9ZhDOBp.sRKat4l14ygu/.LscxrMUcDAfeVOEPiYwbcRkoB09gCmi', '158xxxxxxx',
        'xxxxxxx@gmail.com', '2019-04-04 23:21:27', '2019-04-04 23:21:29');

CREATE TABLE `tb_user_role`
(
    `id`      BIGINT(20) NOT NULL AUTO_INCREMENT,
    `user_id` BIGINT(20) NOT NULL COMMENT '用户 ID',
    `role_id` BIGINT(20) NOT NULL COMMENT '角色 ID',
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 38
  DEFAULT CHARSET = utf8 COMMENT ='用户角色表';
INSERT INTO `tb_user_role`(`id`, `user_id`, `role_id`)
VALUES (37, 37, 37);



# https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql

CREATE TABLE `clientdetails` (
  `appId` varchar(128) NOT NULL,
  `resourceIds` varchar(255) DEFAULT NULL,
  `appSecret` varchar(255) DEFAULT NULL,
  `scope` varchar(255) DEFAULT NULL,
  `grantTypes` varchar(255) DEFAULT NULL,
  `redirectUrl` varchar(255) DEFAULT NULL,
  `authorities` varchar(255) DEFAULT NULL,
  `access_token_validity` int(11) DEFAULT NULL,
  `refresh_token_validity` int(11) DEFAULT NULL,
  `additionalInformation` varchar(4096) DEFAULT NULL,
  `autoApproveScopes` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`appId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

CREATE TABLE `oauth_approvals` (
  `userId` varchar(255) DEFAULT NULL,
  `clientId` varchar(255) DEFAULT NULL,
  `scope` varchar(255) DEFAULT NULL,
  `status` varchar(10) DEFAULT NULL,
  `expiresAt` timestamp NULL DEFAULT NULL,
  `lastModifiedAt` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_client_details` (
  `client_id` varchar(128) NOT NULL,
  `resource_ids` varchar(255) DEFAULT NULL,
  `client_secret` varchar(255) DEFAULT NULL,
  `scope` varchar(255) DEFAULT NULL,
  `authorized_grant_types` varchar(255) DEFAULT NULL,
  `web_server_redirect_uri` varchar(255) DEFAULT NULL,
  `authorities` varchar(255) DEFAULT NULL,
  `access_token_validity` int(11) DEFAULT NULL,
  `refresh_token_validity` int(11) DEFAULT NULL,
  `additional_information` varchar(4096) DEFAULT NULL,
  `autoapprove` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_client_token` (
  `token_id` varchar(255) DEFAULT NULL,
  `token` blob,
  `authentication_id` varchar(128) NOT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `client_id` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`authentication_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_code` (
  `code` varchar(255) DEFAULT NULL,
  `authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

插入SQL数据

client_secret的值是需要加密的
使用Oauth2.0 的密码加密器得到加密后的值

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = OAuthOSSApplication7789.class)
public class OAuthOSSApplication7789Test {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Test
    public void t1(){
        String password = passwordEncoder.encode("123123");
        System.out.println(password);
    }
}
另外导入3个包
		
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            mysql
            mysql-connector-java
        
        
            com.baomidou
            mybatis-plus-boot-starter
        
修改授权服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    // 密码编码器
    @Autowired
    private PasswordEncoder passwordEncoder;
    // 身份验证管理器
    @Autowired
    private AuthenticationManager authenticationManagerBean;

    // jwt
    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;


    //oss(使用datasoure)
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public ClientDetailsService clientDetails() {
        //读取oauth_client_details表
        return new JdbcClientDetailsService(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManagerBean) // 使用密码模式必须配置
                .tokenStore(tokenStore)//配置存储令牌策略
                .accessTokenConverter(jwtAccessTokenConverter)//使用jwt
                .reuseRefreshTokens(false)//refresh_tokens是否重复使用
                .userDetailsService(userDetailsService)//刷新令牌授权是否包含对用户信息的检查
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);//支持get和post请求
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单认证
        security.allowFormAuthenticationForClients()
        // 配置校验token需要带入clientId 和clientSeret配置
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 读取数据库的配置使用oss
        clients.withClientDetails(clientDetails());
    }
}
修改application.yml配置文件
server:
  port: 7787
spring:
  main:
    #允许我们自己覆盖spring放入到IOC容器的对象
    allow-bean-definition-overriding: true
  application:
    name: oauth-oss-server
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/oauth2_sso?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
测试


成功获取token

成功用户信息

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/770537.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号