【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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章