Spring Security OAuth2 入门,linux操作系统学习

本文详细介绍了Spring Security OAuth2的四种授权模式:授权码模式、密码模式、简化模式和客户端模式。通过实例展示了如何配置、获取和使用访问令牌。同时,讨论了刷新令牌的重要性及如何配置和使用,以及令牌的删除操作,遵循了OAuth2 Token撤销(RFC7009)标准。
摘要由CSDN通过智能技术生成
  • 在授权码模式下,允许为空

可能有部分胖友是 Windows 电脑,可以参考 《windows(64位)下使用 curl 命令》 来安装一个 curl 命令。

当然,如果胖友使用 Postman ,可以参看如下两图:

Spring Security OAuth2 入门

  • 图 1

Spring Security OAuth2 入门

  • 图 2

⑥ 调用资源服务器的 API

curl -X GET http://localhost:8080/api/example/hello -H “authorization: Bearer e60e41f2-2ad0-4c79-97d5-49af38e5c2e8”

  • authorization: Bearer e60e41f2-2ad0-4c79-97d5-49af38e5c2e8 处,填写指定的访问令牌类型和访问令牌。例如此处分别为,“Bearer”、“e60e41f2-2ad0-4c79-97d5-49af38e5c2e8” 。

如果胖友使用 Postman ,可以参看如下图:

Spring Security OAuth2 入门

4.2 密码模式

Maven 项目结构如下:

Spring Security OAuth2 入门

Maven 项目结构

对应 GitHub 地址:

https://github.com/YunaiV/SpringBoot-Labs/tree/f8d701cbd9b2a4f2cee3a7f2186148bcdf859895/lab-02/resource-owner-password-credentials-server

① 配置授权服务器

// 授权服务器配置

@Configuration

@EnableAuthorizationServer

public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {

// 用户认证

@Autowired

private AuthenticationManager authenticationManager;

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

endpoints.authenticationManager(authenticationManager);

}

@Override

public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

clients.inMemory()

.withClient(“clientapp”).secret(“112233”) // Client 账号、密码。

.authorizedGrantTypes(“password”) // 密码模式

.scopes(“read_userinfo”, “read_contacts”) // 可授权的 Scope

// .and().withClient() // 可以继续配置新的 Client

;

}

}

  • 配置 Client 的方式,和【授权码模式】基本一致。差别在于:

  • 无需配置 `redirectUris` 属性,因为不需要回调地址。

  • 配置授权模式为【密码模式】。

  • 另外,需要引入 AuthenticationManager 来支持【密码模式】,否则会报 “Resolved [error=“unsupported_grant_type”, error_description=“Unsupported grant type: password”]” 异常。

② 配置登陆账号

和【授权码模式】一致

③ 启动项目

和【授权码模式】一致

④ 获取访问令牌

curl -X POST --user clientapp:112233 http://localhost:8080/oauth/token -H “accept: application/json” -H “content-type: application/x-www-form-urlencoded” -d “grant_type=password&username=yunai&password=1024&scope=read_userinfo”

  • 和【授权码模式】差异比较大。

  • 直接请求 oauth/token 接口,获得访问令牌。

  • 请求参数带上了 username 和 password ,就用户的登陆账号和密码。

  • 请求参数 grant_type 为 password ,表示【密码模式】。

返回结果示例如下:

{

“access_token”: “68de6eb9-5672-4e47-a3e6-110404285ba9”,

“token_type”: “bearer”,

“expires_in”: 43199,

“scope”: “read_userinfo”

}

  • 和【授权码模式】一致。

⑤ 调用资源服务器的 API

和【授权码模式】一致

4.3 简化模式

Maven 项目结构如下:

Spring Security OAuth2 入门

Maven 项目结构

对应 GitHub 地址:

https://github.com/YunaiV/SpringBoot-Labs/tree/f8d701cbd9b2a4f2cee3a7f2186148bcdf859895/lab

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值