[英]How Silhouette JWT token keeps valid in stateless mode?
我正在開發一個項目,並使用Silhouette身份驗證框架。 對於來自瀏覽器UI的常規請求,我使用CookieAuthenticator,對於REST API請求,我使用JWTAuthenticator。 這是包含文檔的Silhouette源代碼的一部分,這使我感到自己不完全了解該工具的工作原理:
/**
* The service that handles the JWT authenticator.
*
* If the authenticator DAO is deactivated then a stateless approach will be used. But note
* that you will loose the possibility to invalidate a JWT.
*
* @param settings The authenticator settings.
* @param dao The DAO to store the authenticator. Set it to None to use a stateless approach.
* @param idGenerator The ID generator used to create the authenticator ID.
* @param clock The clock implementation.
* @param executionContext The execution context to handle the asynchronous operations.
*/
class JWTAuthenticatorService(
settings: JWTAuthenticatorSettings,
dao: Option[AuthenticatorDAO[JWTAuthenticator]],
idGenerator: IDGenerator,
clock: Clock)(implicit val executionContext: ExecutionContext)
extends AuthenticatorService[JWTAuthenticator]
with Logger {
注意文檔的這一部分
如果身份驗證器DAO被禁用,則將使用無狀態方法。 但是請注意*,您將失去使JWT失效的可能性。
因此它的工作恰如他們所說的那樣。 當我將None
作為dao
參數的值傳遞時,即使我關閉了應用程序,生成的令牌仍然有效。 但是沒有后備存儲,這些令牌如何保持有效? 當我再次啟動該應用程序並使用相同的令牌時,它將對用戶進行身份驗證。 而且我不知道它是如何做到的。 你能解釋一下嗎?
非常簡單 您可以使用已知的鹽和算法組合對令牌的內容進行編碼。 JWT令牌具有用HMAC或RSA編碼的已知結構。 服務器可以以無狀態方式解密令牌,例如,只要它們知道編碼密鑰(HMAC的秘密密鑰)和RSA的密鑰對即可。
如果您想變得聰明並查看內部信息,甚至可以自己制作。 JWT是標准化的,並且根據慣例,該帳戶通常可在iss
字段下使用。 例如,在Google Cloud中, iss
是您的Google服務帳戶電子郵件,因此他們可以知道您的身份。
進一步探索,您可以創建自己的session
對象並將其編碼為令牌。
case class Session(user: UUID, timestamp: String, email: String)
// This is roughly the process used.
object TokenEncoder {
val secret = Play.current.configuration.getString("encryption.key")
def encode(session: Session): String = {
// The below line is just to make a point.
AES.encrypt(Json.toJson(session), someSharedKey)
}
def decode(str: String): Option[Session] = {
Json.parse(AES.decrypt(str, someSharedKey)).asOpt[Session]
}
}
然后,如果有跨服務器請求,則可以在cookie或標頭中使用此令牌的字符串值,並且每個服務器可以無狀態地驗證令牌並提取用戶信息,只要他們知道someSharedKey
的值someSharedKey
,用於執行編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.