Spring Security OAuth2四种授权模式总结(七)

news2024/9/21 15:43:45

写在前面:各位看到此博客的小伙伴,如有不对的地方请及时通过私信我或者评论此博客的方式指出,以免误人子弟。多谢!如果我的博客对你有帮助,欢迎进行评论✏️✏️、点赞👍👍、收藏⭐️⭐️,满足一下我的虚荣心💖🙏🙏🙏 。

前面几篇已经搭建好了授权服务uaa和资源服务product,并且也测试过了客户端模式、密码模式,还使用了JWT模式来授权认证,但是还没有记录另外两种模式,这里统一记录一下OAuth2的四种授权模式。

目录

环境搭建

Web安全配置

授权服务器配置

配置客户端信息

配置令牌管理器

配置令牌访问端点

配置令牌端点的安全约束

四种授权模式

授权码模式

简化模式

密码模式

客户端模式

完整代码 

授权服务

Web安全

Token配置


环境搭建

新建oauth2服务,引入如下依赖:

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>

Web安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin").hasAuthority("admin")
                .antMatchers("/common").permitAll()
                .anyRequest().authenticated()
                .and().formLogin()
                .and().csrf().disable();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("zhangsan")
                .password(passwordEncoder().encode("123456"))
                .roles("common");
    }

}

授权服务器配置

配置客户端信息

这里为了快速的将整个流程记录完整,客户端信息及后面用到的用户信息都存在内存中。

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("dev-client")
                .secret(new BCryptPasswordEncoder().encode("123456"))
                // 资源列表
                .resourceIds("product-service")
                // 此客户端允许的授权类型
                .authorizedGrantTypes("authorization_code","client_credentials", "password","implicit","refresh_token")
                // 用来限制客户端的访问范围 如果为空(默认) 那么客户端拥有全部的访问范围
                .scopes("all")
                // 跳转到授权页面
                .autoApprove(false)
                // 验证回调地址
                .redirectUris("https://www.baidu.com");
    }

配置令牌管理器


    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(tokenStore());
        // 有效期10秒
        tokenServices.setAccessTokenValiditySeconds(10);
        // 刷新令牌默认有效期3天
        tokenServices.setRefreshTokenValiditySeconds(10);
        return tokenServices;
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

配置令牌访问端点

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        // 密码模式需要
        endpoints.authenticationManager(authenticationManager);
        // 授权码模式需要
        endpoints.authorizationCodeServices(authorizationCodeServices());
        // 令牌管理服务
        endpoints.tokenServices(tokenServices());

    }

    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }

配置令牌端点的安全约束

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

四种授权模式

授权码模式

步骤一

申请授权码,资源拥有者打开客户端,客户端要求资源拥有者给预授权,它将浏览器重定向到授权服务器,重定向时会附加客户端的身份信息,如:

http://localhost:9005/oauth/authorize?client_id=dev-client&response_type=code&scope=all&redirect_uri=https://www.baidu.com

参数列表如下:

  • client_id:客户端标识。
  • response_code:授权码模式固定为code。
  • scope:客户端权限范围。
  • redirect_uri:跳转uri,当授权码申请成功后会跳转到此地址,并在后边带上code参数。

步骤二

浏览器出现向授权服务器授权页面,之后用户同意授权。

步骤三

授权服务器将授权码经浏览器发送给client(通过redirect_uri)。

步骤四

客户端拿着授权码想授权服务器申请token,请求如下:

http://localhost:9005/oauth/token?client_id=dev-client&client_secret=123456&grant_type=authorization_code&code=WZQWSI&redirect_uri=https://www.baidu.com

参数列表如下:

  • client_id:客户端标识。
  • client_secret:客户端密钥。
  • grant_type:授权类型,填写authorization_code
  • code:授权码,授权码只使用一次就失效。
  • redirect_uri:申请授权码时的跳转url。

步骤五

授权服务器返回令牌(access_token)。

这种模式是四种模式中最安全的,一般用于client是Web服务器端应用或第三方App调用资源服务的时候,因为在这种模式中access_token不经过浏览器或者移动端的App,而是直接从服务端去交换,这样就最大限度的减少了令牌泄露的风险。

测试

浏览器访问认证页面,如下:

http://localhost:9005/oauth/authorize?client_id=dev-client&response_type=code&scope=all&redirect_uri=https://www.baidu.com

 输入账号:zhangsan  密码:123456,登录进入授权页面:

 确认授权后,浏览器会重定向到指定路径并附加验证码,code每次都不一样,最后使用该code获取token。

使用该code申请令牌,如下:

 上面的username和password带不带都可以,返回结果如下:

{

    "access_token": "31482019-12af-47d7-be87-a9db014e5ac0",

    "token_type": "bearer",

    "refresh_token": "b1a28869-e0b8-4825-8158-9454acd233b6",

    "expires_in": 9,

    "scope": "all"

}

可能你会遇到返回没有refresh_token的情况,检查下你配置的token管理器中是否配置了支持刷新令牌,如果不配置的话就不会返回refresh_token,我上面配置了才会返回,如下:

tokenServices.setSupportRefreshToken(true);

简化模式

步骤一

资源拥有者打开客户端,客户端要求资源拥有者给预授权,它将浏览器重定向到授权服务器,重定向时会附加客户端的身份信息,如:

http://localhost:9005/oauth/authorize?client_id=dev-client&response_type=token&scope=all&redirect_uri=https://www.baidu.com

参数同授权码模式,将response_type改为token即可。 

步骤二

浏览器出现向授权服务器授权页面,之后用户同意授权。

步骤三

授权服务器将授权码和令牌到重定向uri之后。

测试

浏览器访问认证页面:

http://localhost:9005/oauth/authorize?client_id=dev-client&response_type=token&scope=all&redirect_uri=https://www.baidu.com

 输入账号:zhangsan  密码:123456,登录进入授权页面:

 确认授权后,浏览器会重定向到指定的redirect_uri路径,并将token存放在uri路径之后。

https://www.baidu.com/#access_token=e37c71d2-60fd-4ba1-9bc5-92ebc986ce56&token_type=bearer&expires_in=9

密码模式

步骤一

资源拥有者将用户名、密码发送给客户端。

步骤二

客户端拿着资源拥有者的用户名、密码向授权服务器请求令牌,如下:

localhost:9005/oauth/token?client_id=dev-client&client_secret=123456&grant_type=password&scopes=all&username=zhangsan&password=123456

参数列表如下:

  • client_id:客户端标识。
  • client_secret:客户端密钥。
  • grant_type:授权类型,填写password。
  • username:资源拥有者用户名。
  • password:资源拥有者密码。

步骤三

授权服务器将令牌发送给client。

这种模式十分简单,但直接将用户敏感信息泄露给了client,因此这就说明这种模式只能用于client是我们自己开发的情况下。

测试

请求令牌,如下:

返回如下: 

{

    "access_token": "3c79f517-b725-48cc-a7b2-98613909b43a",

    "token_type": "bearer",

    "expires_in": 9,

    "scope": "all"

}

客户端模式

步骤一

客户端向授权服务器发送自己的身份信息,并请求令牌。

步骤二

确认客户端身份无误后,将令牌发送给client,请求如下:

localhost:9005/oauth/token?client_id=dev-client&client_secret=123456&grant_type=client_credentials&scopes=all

参数列表如下:

  • client_id:客户端标识。
  • client_secret:客户端密钥。
  • grant_type:授权类型,填写client_credentials。

 这种模式是最方便但最不安全的模式。

因此这就要求我们对client完全信任,而client本身也是安全的,因此这种模式一般用来提供给我们完全信任的服务端使用。

测试

请求令牌,如下:

返回如下:

{

    "access_token": "3f064d7b-aaeb-4d7f-a7e8-e9b8a3aa627a",

    "token_type": "bearer",

    "expires_in": 9,

    "scope": "all"

}

完整代码 

授权服务

@EnableAuthorizationServer
@Configuration
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("dev-client")
                .secret(new BCryptPasswordEncoder().encode("123456"))
                // 资源列表
                .resourceIds("product-service")
                // 此客户端允许的授权类型
                .authorizedGrantTypes("authorization_code", "client_credentials", "password", "implicit", "refresh_token")
                // 用来限制客户端的访问范围 如果为空(默认) 那么客户端拥有全部的访问范围
                .scopes("all")
                // 跳转到授权页面
                .autoApprove(false)
                // 验证回调地址
                .redirectUris("https://www.baidu.com");
//        clients.withClientDetails(clientDetails());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        // 密码模式需要
        endpoints.authenticationManager(authenticationManager);
        // 授权码模式需要
        endpoints.authorizationCodeServices(authorizationCodeServices());
        // 令牌管理服务
        endpoints.tokenServices(tokenServices());

    }

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

    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(tokenStore);
        // 有效期10秒
        tokenServices.setAccessTokenValiditySeconds(10);
        // 刷新令牌默认有效期3天
        tokenServices.setRefreshTokenValiditySeconds(10);
        return tokenServices;
    }

    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }

}

Web安全

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/ignore");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin").hasAuthority("admin")
                .antMatchers("/common").permitAll()
                .anyRequest().authenticated()
                .and().formLogin()
                .and().csrf().disable();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("zhangsan")
                .password(passwordEncoder().encode("123456"))
                .roles("common");
    }

}

Token配置

@Configuration
public class TokenConfig {

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/352017.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【MySQL】MySQL表的增删改查(CRUD)

✨个人主页&#xff1a;bit me&#x1f447; ✨当前专栏&#xff1a;MySQL数据库&#x1f447; ✨算法专栏&#xff1a;算法基础&#x1f447; ✨每日一语&#xff1a;生命久如暗室&#xff0c;不碍朝歌暮诗 目 录&#x1f513;一. CRUD&#x1f512;二. 新增&#xff08;Creat…

将array中元素四舍五入取整的np.rint()方法

【小白从小学Python、C、Java】 【计算机等级考试500强双证书】 【Python-数据分析】 将array中元素四舍五入取整 np.rint()方法 选择题 关于以下python代码说法错误的一项是? import numpy as np a np.array([-1.7, 1.5, -0.2, 0.3]) print("【显示】a\n",a) pr…

BI是报表?BI是可视化?BI到底是什么?

很多企业认为只要买一个前端商业智能BI分析工具就可以解决企业级的商业智能BI所有问题&#xff0c;这个看法实际上也不可行的。可能在最开始分析场景相对简单&#xff0c;对接数据的复杂度不是很高的情况下这类商业智能BI分析工具没有问题。但是在企业的商业智能BI项目建设有一…

数字化系统使用率低的原因剖析

当“数字化变革”成为热门话题&#xff0c;当“数字化转型”作为主题频频出现在一个个大型会议中&#xff0c;我们知道数字化时代的确到来了。但是&#xff0c;根据Gartner的报告我们看到一个矛盾的现象——85%的企业数字化建设与应用并不理想、但对数字化系统的需求多年来持续…

软件测试项目实战(附全套实战项目教程+视频+源码)

开通博客以来&#xff0c;我更新了很多实战项目&#xff0c;但一部分小伙伴在搭建环境时遇到了问题。 于是&#xff0c;我收集了一波高频问题&#xff0c;汇成本篇&#xff0c;供大家参考&#xff0c;避免重复踩坑。 如果你还遇到过其他坑和未解决的问题&#xff0c;可在评论区…

webpack安装步骤(一)

系列文章目录 安装步骤系列文章目录前言一、Webpack是什么&#xff1f;Webpack官网解释解释内容如下图二、Webpack的安装步骤第一步&#xff1a;检查本机是否已经安装过Webpack&#xff08;全局&#xff09;1.操作如下2.结果如下图第二步&#xff1a;安装webpack&#xff08;非…

利用无线通讯技术构建工厂智能化立体仓储

立体仓库主要通过检测、信息识别、控制、通信、监控调度、大屏显示及计算机管理等装置组成。完成仓库各设备连接无线化&#xff0c;可大幅减少网线布防成本&#xff0c;缩短生产线调度时间&#xff0c;实现汽车装配生产线的柔性生产&#xff0c;提高汽车装配生产的自动化水平。…

短视频的素材在哪里找呢?推荐给你一个好办法

我刚刚在视频号做出了30万播放的小爆款&#xff0c;过去3年我做出了很多6位数播放的视频。在这里&#xff0c;我就大家分享20个我常用的素材渠道&#xff0c;其中一些渠道比较小众。除此之外&#xff0c;我也希望同时讲一下短视频的内容生产。为了方便大家浏览&#xff0c;我把…

使用web3连接Georli测试网络

文章目录1.使用geth方式在终端2.写成脚本2.1 通过metamask &#xff08;现成的太复杂&#xff0c;搞不太来&#xff09;2.2 通过自己的接口3.通过truffle方式连接 &#xff08;不成功&#xff09;目前的工作情况是&#xff0c;已在remix写好执行合约并部署在Georli测试网络中&a…

NJ 时钟自动调整功能(SNTP)

NJ 时钟自动调整功能(SNTP) 实验设备&#xff1a;NJ501-1300 实验目的&#xff1a;NJ使用ntp实现时钟自动调整 1. 实验概览 ​ 本次实验通过NJ的ntp功能&#xff0c;将PLC的时钟和阿里的ntp服务器时钟每隔1分钟同步一次。 阿里ntp服务器的域名为&#xff1a;ntp.aliyun.com…

Python fileinput模块:逐行读取多个文件

前面章节中&#xff0c;我们学会了使用 open() 和 read()&#xff08;或者 readline()、readlines() &#xff09;组合&#xff0c;来读取单个文件中的数据。但在某些场景中&#xff0c;可能需要读取多个文件的数据&#xff0c;这种情况下&#xff0c;再使用这个组合&#xff0…

力扣56.合并区间

文章目录力扣56.合并区间题目描述排序合并力扣56.合并区间 题目描述 以数组 intervals 表示若干个区间的集合&#xff0c;其中单个区间为 intervals[i] [starti, endi] 。请你合并所有重叠的区间&#xff0c;并返回 一个不重叠的区间数组&#xff0c;该数组需恰好覆盖输入中…

windows上配置IIS全过程

文章目录1️⃣ 配置IIS1.1 从开始打开服务器管理1.2 添加角色和功能1.3 添加角色和功能向导1.4 按照如下步骤选择2️⃣ 问题&#xff1a;缺少源文件解决方案优质资源分享作者&#xff1a;xcLeigh 文章地址&#xff1a;https://blog.csdn.net/weixin_43151418/article/details/1…

与感受野相关的几种网络结构

一、Inception 1. Inception v1 目的 通过设计一个稀疏网络结构&#xff0c;但是能够产生稠密的数据&#xff0c;既能增加神经网络表现&#xff0c;又能保证计算资源的使用效率。 结构 图1-1 Inception v1结构图 特点 共4个通道&#xff0c;其中3个卷积通道分别使用111111…

HashTable和HashMap的区别详解

一、HashMap简介 HashMap是基于哈希表实现的&#xff0c;每一个元素是一个key-value对&#xff0c;其内部通过单链表解决冲突问题&#xff0c;容量不足&#xff08;超过了阀值&#xff09;时&#xff0c;同样会自动增长。 HashMap是非线程安全的&#xff0c;只是用于单线程环境…

Velocity实战笔记

基础准备 velocity模板语法简介 官方实例 版本环境 <dependency><groupId>org.apache.velocity</groupId><artifactId>velocity</artifactId><version>1.7</version></dependency>标签介绍 <Workbook><DocumentPr…

STM32 DFU模式烧录代码

什么是DFU? dfu的本质是isp&#xff0c;usb接口的isp&#xff0c;在系统编程&#xff0c;进入isp的方式我们先了解 如下图 boot0为高电平 boot1为低电平即可进入isp模式。 熟悉的场景 在我们使用flymcu软件下载代码时&#xff0c;本质也是isp 串口接口的isp。 傻瓜使用方式…

RF电路的分布参数集中参数化

文章目录1.威尔金森功分器的集总参数设计例1&#xff1a;ADS仿真:设计一个工作在1GHz的威尔金森功分器2.分支线定向耦合器的集总参数设计例2&#xff1a;ADS仿真设计一个分支线的定向耦合器&#xff0c;中心频率&#xff1a;920MHz3.总结射频电路的分析会引入分布参数分析的理论…

刷题专练之翻转题练习

文章目录一、 编写函数实现字符串翻转二、轮转数组总结一、 编写函数实现字符串翻转 描述 编写一个函数&#xff0c;实现字符串的翻转 输入描述&#xff1a; 输入一个字符串 输出描述&#xff1a; 输出翻转后的字符串 写法一&#xff1a; 这种方法是定义begin和end&#xff0…

Nacos详细使用操作文档(图文详细)

文章目录Nacos详细使用操作文档(图文详细)1、安装2、Nacos作为注册中心2.1、Nacos服务注册【ICRMS】2.2、Nacos 服务调用2.2.1、Feign 远程调用【Personnel】2.2.2)、RestTemplateRibbon 远程调用【Personnel】3、Nacos作为配置中心4、Nacos 命令空间5、Nacos配置文件参数详解N…