【Spring Security】Spring Security Oauth2密码模式授权


在这里插入图片描述

密码模式(Resource Owner Password Credentials)与授权码模式的区别是申请令牌不再使用授权码,而是直接通过用户名和密码即可申请令牌。

github:https://github.com/fafeidou/fast-cloud-nacos/blob/master/fast-cloud-nacos-examples/spring-security-examples/pom.xml

1. 通过用户名和密码申请令牌

  • Post请求:http://localhost:40400/auth/oauth/token
    参数:
    grant_type:密码模式授权填写password
    username:账号
    password:密码
    并且此链接需要使用 http Basic认证。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
注意:当令牌没有过期时同一个用户再次申请令牌则不再颁发新令牌。
追踪源码可以找到endpoint: org.springframework.security.oauth2.provider.endpoint.token#postAccessToken

2. 校验令牌

Spring Security Oauth2提供校验令牌的端点,如下:
Get: http://localhost:40400/auth/oauth/check_token?token=
参数:
token:令牌
使用postman测试如下:
在这里插入图片描述
结果如下:

{
    "companyId": null,
    "userpic": null,
    "user_name": "batman",
    "scope": [
        "app"
    ],
    "name": null,
    "utype": null,
    "id": null,
    "exp": 1577114103,
    "jti": "2981dbfa-724b-46a0-acd9-9f47ee1c2c15",
    "client_id": "batman"
}

exp:过期时间,long类型,距离1970年的秒数(new Date().getTime()可得到当前时间距离1970年的毫秒数)。
user_name: 用户名
client_id:客户端Id,在oauth_client_details中配置
scope:客户端范围,在oauth_client_details表中配置
jti:与令牌对应的唯一标识companyId、userpic、name、utype、id:这些字段是本认证服务在Spring Security基础上扩展的用户身份信息

endpoint所在位置 :org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint#checkToken

3. 刷新令牌

刷新令牌是当令牌快过期时重新生成一个令牌,它于授权码授权和密码授权生成令牌不同,刷新令牌不需要授权码也不需要账号和密码,只需要一个刷新令牌、客户端id和客户端密码。
测试如下:
Post:http://localhost:40400/auth/oauth/token
参数:
grant_type: 固定为 refresh_token
refresh_token:刷新令牌(注意不是access_token,而是refresh_token)
在这里插入图片描述
刷新令牌成功,会重新生成新的访问令牌和刷新令牌,令牌的有效期也比旧令牌长。刷新令牌通常是在令牌快过期时进行刷新。这个endpoint和获取token是同一个接口。

发布了97 篇原创文章 · 获赞 100 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章