更新依赖项,优化 OAuth2 服务,添加 PKCE 支持,增强 OIDC 处理器,新增客户端注册和令牌管理端点,改进数据库模型以支持新功能。
This commit is contained in:
211
services/client.go
Normal file
211
services/client.go
Normal file
@@ -0,0 +1,211 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"oidc-oauth2-server/models"
|
||||
)
|
||||
|
||||
type ClientService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
type ClientResponse struct {
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret string `json:"client_secret,omitempty"`
|
||||
RegistrationAccessToken string `json:"registration_access_token,omitempty"`
|
||||
RegistrationClientURI string `json:"registration_client_uri,omitempty"`
|
||||
ClientIDIssuedAt time.Time `json:"client_id_issued_at"`
|
||||
ClientSecretExpiresAt time.Time `json:"client_secret_expires_at"`
|
||||
RedirectURIs []string `json:"redirect_uris"`
|
||||
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
|
||||
GrantTypes []string `json:"grant_types"`
|
||||
ResponseTypes []string `json:"response_types"`
|
||||
ClientName string `json:"client_name"`
|
||||
ClientURI string `json:"client_uri"`
|
||||
LogoURI string `json:"logo_uri"`
|
||||
Scope string `json:"scope"`
|
||||
Contacts []string `json:"contacts"`
|
||||
TosURI string `json:"tos_uri"`
|
||||
PolicyURI string `json:"policy_uri"`
|
||||
SoftwareID string `json:"software_id"`
|
||||
SoftwareVersion string `json:"software_version"`
|
||||
}
|
||||
|
||||
type ClientRegistrationRequest struct {
|
||||
RedirectURIs []string `json:"redirect_uris" binding:"required"`
|
||||
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
|
||||
GrantTypes []string `json:"grant_types"`
|
||||
ResponseTypes []string `json:"response_types"`
|
||||
ClientName string `json:"client_name"`
|
||||
ClientURI string `json:"client_uri"`
|
||||
LogoURI string `json:"logo_uri"`
|
||||
Scope string `json:"scope"`
|
||||
Contacts []string `json:"contacts"`
|
||||
TosURI string `json:"tos_uri"`
|
||||
PolicyURI string `json:"policy_uri"`
|
||||
SoftwareID string `json:"software_id"`
|
||||
SoftwareVersion string `json:"software_version"`
|
||||
}
|
||||
|
||||
func NewClientService(db *gorm.DB) *ClientService {
|
||||
return &ClientService{db: db}
|
||||
}
|
||||
|
||||
func (s *ClientService) RegisterClient(req *ClientRegistrationRequest) (*ClientResponse, error) {
|
||||
// 生成客户端凭证
|
||||
clientID := generateSecureToken(32)
|
||||
clientSecret := generateSecureToken(48)
|
||||
|
||||
// 设置默认值
|
||||
if len(req.GrantTypes) == 0 {
|
||||
req.GrantTypes = []string{"authorization_code"}
|
||||
}
|
||||
if len(req.ResponseTypes) == 0 {
|
||||
req.ResponseTypes = []string{"code"}
|
||||
}
|
||||
if req.TokenEndpointAuthMethod == "" {
|
||||
req.TokenEndpointAuthMethod = "client_secret_basic"
|
||||
}
|
||||
|
||||
// 将字符串数组转换为 JSON
|
||||
redirectURIsJSON, _ := json.Marshal(req.RedirectURIs)
|
||||
grantTypesJSON, _ := json.Marshal(req.GrantTypes)
|
||||
responseTypesJSON, _ := json.Marshal(req.ResponseTypes)
|
||||
scopesJSON, _ := json.Marshal([]string{req.Scope})
|
||||
contactsJSON, _ := json.Marshal(req.Contacts)
|
||||
|
||||
// 创建客户端记录
|
||||
client := &models.Client{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
RedirectURIs: datatypes.JSON(redirectURIsJSON),
|
||||
TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
|
||||
GrantTypes: datatypes.JSON(grantTypesJSON),
|
||||
ResponseTypes: datatypes.JSON(responseTypesJSON),
|
||||
ClientName: req.ClientName,
|
||||
ClientURI: req.ClientURI,
|
||||
LogoURI: req.LogoURI,
|
||||
Scopes: datatypes.JSON(scopesJSON),
|
||||
Contacts: datatypes.JSON(contactsJSON),
|
||||
TosURI: req.TosURI,
|
||||
PolicyURI: req.PolicyURI,
|
||||
SoftwareID: req.SoftwareID,
|
||||
SoftwareVersion: req.SoftwareVersion,
|
||||
IsActive: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.db.Create(client).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 构建响应
|
||||
return &ClientResponse{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
ClientIDIssuedAt: client.CreatedAt,
|
||||
ClientSecretExpiresAt: time.Time{}, // 永不过期
|
||||
RedirectURIs: req.RedirectURIs,
|
||||
TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
|
||||
GrantTypes: req.GrantTypes,
|
||||
ResponseTypes: req.ResponseTypes,
|
||||
ClientName: req.ClientName,
|
||||
ClientURI: req.ClientURI,
|
||||
LogoURI: req.LogoURI,
|
||||
Scope: req.Scope,
|
||||
Contacts: req.Contacts,
|
||||
TosURI: req.TosURI,
|
||||
PolicyURI: req.PolicyURI,
|
||||
SoftwareID: req.SoftwareID,
|
||||
SoftwareVersion: req.SoftwareVersion,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ClientService) GetClient(clientID string) (*ClientResponse, error) {
|
||||
var client models.Client
|
||||
if err := s.db.Where("client_id = ? AND is_active = ?", clientID, true).First(&client).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 解析 JSON 字段
|
||||
var redirectURIs, grantTypes, responseTypes, scopes, contacts []string
|
||||
json.Unmarshal(client.RedirectURIs, &redirectURIs)
|
||||
json.Unmarshal(client.GrantTypes, &grantTypes)
|
||||
json.Unmarshal(client.ResponseTypes, &responseTypes)
|
||||
json.Unmarshal(client.Scopes, &scopes)
|
||||
json.Unmarshal(client.Contacts, &contacts)
|
||||
|
||||
return &ClientResponse{
|
||||
ClientID: client.ClientID,
|
||||
ClientIDIssuedAt: client.CreatedAt,
|
||||
RedirectURIs: redirectURIs,
|
||||
TokenEndpointAuthMethod: client.TokenEndpointAuthMethod,
|
||||
GrantTypes: grantTypes,
|
||||
ResponseTypes: responseTypes,
|
||||
ClientName: client.ClientName,
|
||||
ClientURI: client.ClientURI,
|
||||
LogoURI: client.LogoURI,
|
||||
Scope: scopes[0],
|
||||
Contacts: contacts,
|
||||
TosURI: client.TosURI,
|
||||
PolicyURI: client.PolicyURI,
|
||||
SoftwareID: client.SoftwareID,
|
||||
SoftwareVersion: client.SoftwareVersion,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ClientService) UpdateClient(clientID string, req *ClientRegistrationRequest) (*ClientResponse, error) {
|
||||
var client models.Client
|
||||
if err := s.db.Where("client_id = ? AND is_active = ?", clientID, true).First(&client).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 将字符串数组转换为 JSON
|
||||
redirectURIsJSON, _ := json.Marshal(req.RedirectURIs)
|
||||
grantTypesJSON, _ := json.Marshal(req.GrantTypes)
|
||||
responseTypesJSON, _ := json.Marshal(req.ResponseTypes)
|
||||
scopesJSON, _ := json.Marshal([]string{req.Scope})
|
||||
contactsJSON, _ := json.Marshal(req.Contacts)
|
||||
|
||||
// 更新客户端信息
|
||||
client.RedirectURIs = datatypes.JSON(redirectURIsJSON)
|
||||
client.GrantTypes = datatypes.JSON(grantTypesJSON)
|
||||
client.ResponseTypes = datatypes.JSON(responseTypesJSON)
|
||||
client.Scopes = datatypes.JSON(scopesJSON)
|
||||
client.Contacts = datatypes.JSON(contactsJSON)
|
||||
client.UpdatedAt = time.Now()
|
||||
|
||||
if err := s.db.Save(&client).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetClient(clientID)
|
||||
}
|
||||
|
||||
func (s *ClientService) DeleteClient(clientID string) error {
|
||||
result := s.db.Model(&models.Client{}).Where("client_id = ?", clientID).Update("is_active", false)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("client not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateSecureToken(length int) string {
|
||||
b := make([]byte, length)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return ""
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
75
services/keys.go
Normal file
75
services/keys.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
type KeyManager struct {
|
||||
privateKey *rsa.PrivateKey
|
||||
publicKey *rsa.PublicKey
|
||||
kid string
|
||||
}
|
||||
|
||||
type JSONWebKey struct {
|
||||
Kty string `json:"kty"`
|
||||
Kid string `json:"kid"`
|
||||
Use string `json:"use"`
|
||||
N string `json:"n"`
|
||||
E string `json:"e"`
|
||||
Alg string `json:"alg"`
|
||||
}
|
||||
|
||||
type JSONWebKeySet struct {
|
||||
Keys []JSONWebKey `json:"keys"`
|
||||
}
|
||||
|
||||
func NewKeyManager() (*KeyManager, error) {
|
||||
// 生成 RSA 密钥对
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate RSA key: %v", err)
|
||||
}
|
||||
|
||||
// 生成密钥 ID
|
||||
kid := generateKeyID()
|
||||
|
||||
return &KeyManager{
|
||||
privateKey: privateKey,
|
||||
publicKey: &privateKey.PublicKey,
|
||||
kid: kid,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (km *KeyManager) GetJWKS() (*JSONWebKeySet, error) {
|
||||
// 将公钥转换为 JWK 格式
|
||||
jwk := JSONWebKey{
|
||||
Kty: "RSA",
|
||||
Kid: km.kid,
|
||||
Use: "sig",
|
||||
Alg: "RS256",
|
||||
N: base64.RawURLEncoding.EncodeToString(km.publicKey.N.Bytes()),
|
||||
E: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(km.publicKey.E)).Bytes()),
|
||||
}
|
||||
|
||||
return &JSONWebKeySet{
|
||||
Keys: []JSONWebKey{jwk},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (km *KeyManager) GetPrivateKey() *rsa.PrivateKey {
|
||||
return km.privateKey
|
||||
}
|
||||
|
||||
func (km *KeyManager) GetKID() string {
|
||||
return km.kid
|
||||
}
|
||||
|
||||
func generateKeyID() string {
|
||||
b := make([]byte, 16)
|
||||
rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
@@ -2,8 +2,11 @@ package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
@@ -13,17 +16,20 @@ import (
|
||||
)
|
||||
|
||||
type OAuthService struct {
|
||||
db *gorm.DB
|
||||
jwtSecret []byte
|
||||
tokenTTL time.Duration
|
||||
db *gorm.DB
|
||||
keyManager *KeyManager
|
||||
tokenTTL time.Duration
|
||||
}
|
||||
|
||||
type AuthorizeRequest struct {
|
||||
ResponseType string
|
||||
ClientID string
|
||||
RedirectURI string
|
||||
Scope string
|
||||
State string
|
||||
ResponseType string
|
||||
ClientID string
|
||||
RedirectURI string
|
||||
Scope string
|
||||
State string
|
||||
CodeChallenge string
|
||||
CodeChallengeMethod string
|
||||
Nonce string
|
||||
}
|
||||
|
||||
type TokenRequest struct {
|
||||
@@ -32,6 +38,7 @@ type TokenRequest struct {
|
||||
RedirectURI string
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
CodeVerifier string
|
||||
}
|
||||
|
||||
type TokenResponse struct {
|
||||
@@ -42,12 +49,17 @@ type TokenResponse struct {
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
}
|
||||
|
||||
func NewOAuthService(db *gorm.DB, jwtSecret []byte) *OAuthService {
|
||||
return &OAuthService{
|
||||
db: db,
|
||||
jwtSecret: jwtSecret,
|
||||
tokenTTL: time.Hour,
|
||||
func NewOAuthService(db *gorm.DB) (*OAuthService, error) {
|
||||
keyManager, err := NewKeyManager()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &OAuthService{
|
||||
db: db,
|
||||
keyManager: keyManager,
|
||||
tokenTTL: time.Hour,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *OAuthService) ValidateAuthorizeRequest(req *AuthorizeRequest) error {
|
||||
@@ -61,8 +73,13 @@ func (s *OAuthService) ValidateAuthorizeRequest(req *AuthorizeRequest) error {
|
||||
}
|
||||
|
||||
// 验证重定向 URI
|
||||
var redirectURIs []string
|
||||
if err := json.Unmarshal(client.RedirectURIs, &redirectURIs); err != nil {
|
||||
return errors.New("invalid redirect URIs format")
|
||||
}
|
||||
|
||||
validRedirect := false
|
||||
for _, uri := range client.RedirectURIs {
|
||||
for _, uri := range redirectURIs {
|
||||
if uri == req.RedirectURI {
|
||||
validRedirect = true
|
||||
break
|
||||
@@ -72,6 +89,16 @@ func (s *OAuthService) ValidateAuthorizeRequest(req *AuthorizeRequest) error {
|
||||
return errors.New("invalid redirect URI")
|
||||
}
|
||||
|
||||
// 验证 PKCE
|
||||
if req.CodeChallenge != "" {
|
||||
if req.CodeChallengeMethod != "S256" && req.CodeChallengeMethod != "plain" {
|
||||
return errors.New("invalid code challenge method")
|
||||
}
|
||||
if len(req.CodeChallenge) < 43 || len(req.CodeChallenge) > 128 {
|
||||
return errors.New("invalid code challenge length")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -84,13 +111,16 @@ func (s *OAuthService) GenerateAuthorizationCode(userID uint, req *AuthorizeRequ
|
||||
code := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
authCode := &models.AuthorizationCode{
|
||||
Code: code,
|
||||
ClientID: req.ClientID,
|
||||
RedirectURI: req.RedirectURI,
|
||||
UserID: userID,
|
||||
Scope: req.Scope,
|
||||
ExpiresAt: time.Now().Add(10 * time.Minute),
|
||||
Used: false,
|
||||
Code: code,
|
||||
ClientID: req.ClientID,
|
||||
RedirectURI: req.RedirectURI,
|
||||
UserID: userID,
|
||||
Scope: req.Scope,
|
||||
ExpiresAt: time.Now().Add(10 * time.Minute),
|
||||
Used: false,
|
||||
CodeChallenge: req.CodeChallenge,
|
||||
CodeChallengeMethod: req.CodeChallengeMethod,
|
||||
Nonce: req.Nonce,
|
||||
}
|
||||
|
||||
// 保存授权码到数据库
|
||||
@@ -119,6 +149,17 @@ func (s *OAuthService) ExchangeToken(req *TokenRequest) (*TokenResponse, error)
|
||||
return nil, errors.New("redirect URI mismatch")
|
||||
}
|
||||
|
||||
// 验证 PKCE
|
||||
if authCode.CodeChallenge != "" {
|
||||
if req.CodeVerifier == "" {
|
||||
return nil, errors.New("code verifier required")
|
||||
}
|
||||
|
||||
if err := validatePKCE(authCode.CodeChallenge, authCode.CodeChallengeMethod, req.CodeVerifier); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// 验证客户端
|
||||
client := &models.Client{}
|
||||
if err := s.db.Where("client_id = ? AND client_secret = ?",
|
||||
@@ -139,7 +180,7 @@ func (s *OAuthService) ExchangeToken(req *TokenRequest) (*TokenResponse, error)
|
||||
}
|
||||
|
||||
// 生成 ID 令牌
|
||||
idToken, err := s.generateIDToken(user, client, authCode.Scope)
|
||||
idToken, err := s.generateIDToken(user, client, authCode.Scope, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -167,20 +208,56 @@ func (s *OAuthService) generateAccessToken(user *models.User, client *models.Cli
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(s.jwtSecret)
|
||||
return token.SignedString(s.keyManager.GetPrivateKey())
|
||||
}
|
||||
|
||||
func (s *OAuthService) generateIDToken(user *models.User, client *models.Client, scope string) (string, error) {
|
||||
func (s *OAuthService) generateIDToken(user *models.User, client *models.Client, scope string, nonce string) (string, error) {
|
||||
now := time.Now()
|
||||
claims := jwt.MapClaims{
|
||||
"sub": user.ID,
|
||||
"iss": client.ClientID,
|
||||
"sub": fmt.Sprintf("%d", user.ID),
|
||||
"aud": client.ClientID,
|
||||
"exp": now.Add(s.tokenTTL).Unix(),
|
||||
"iat": now.Unix(),
|
||||
"iss": client.ClientID,
|
||||
"auth_time": now.Unix(),
|
||||
"nonce": nonce,
|
||||
"acr": "1",
|
||||
"email": user.Email,
|
||||
"email_verified": true,
|
||||
"name": user.Username,
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(s.jwtSecret)
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||||
token.Header["kid"] = s.keyManager.GetKID()
|
||||
|
||||
return token.SignedString(s.keyManager.GetPrivateKey())
|
||||
}
|
||||
|
||||
func validatePKCE(challenge, method, verifier string) error {
|
||||
if len(verifier) < 43 || len(verifier) > 128 {
|
||||
return errors.New("invalid code verifier length")
|
||||
}
|
||||
|
||||
var computedChallenge string
|
||||
if method == "S256" {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(verifier))
|
||||
computedChallenge = base64.RawURLEncoding.EncodeToString(h.Sum(nil))
|
||||
} else {
|
||||
computedChallenge = verifier
|
||||
}
|
||||
|
||||
if computedChallenge != challenge {
|
||||
return errors.New("code verifier does not match challenge")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OAuthService) GetJWKS() (*JSONWebKeySet, error) {
|
||||
return s.keyManager.GetJWKS()
|
||||
}
|
||||
|
||||
func (s *OAuthService) GetKeyManager() *KeyManager {
|
||||
return s.keyManager
|
||||
}
|
||||
|
||||
114
services/token.go
Normal file
114
services/token.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TokenService struct {
|
||||
db *gorm.DB
|
||||
keyManager *KeyManager
|
||||
}
|
||||
|
||||
type TokenInfo struct {
|
||||
Active bool `json:"active"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
ClientID string `json:"client_id,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
TokenType string `json:"token_type,omitempty"`
|
||||
Exp int64 `json:"exp,omitempty"`
|
||||
Iat int64 `json:"iat,omitempty"`
|
||||
Nbf int64 `json:"nbf,omitempty"`
|
||||
Sub string `json:"sub,omitempty"`
|
||||
Aud string `json:"aud,omitempty"`
|
||||
Iss string `json:"iss,omitempty"`
|
||||
Jti string `json:"jti,omitempty"`
|
||||
}
|
||||
|
||||
type RevokedToken struct {
|
||||
gorm.Model
|
||||
Token string `gorm:"uniqueIndex;not null"`
|
||||
ExpiresAt time.Time `gorm:"not null"`
|
||||
}
|
||||
|
||||
func NewTokenService(db *gorm.DB, keyManager *KeyManager) *TokenService {
|
||||
return &TokenService{
|
||||
db: db,
|
||||
keyManager: keyManager,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TokenService) RevokeToken(token, tokenTypeHint string) error {
|
||||
// 验证令牌
|
||||
claims, err := s.parseToken(token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 保存到撤销列表
|
||||
revokedToken := &RevokedToken{
|
||||
Token: token,
|
||||
ExpiresAt: time.Unix(claims["exp"].(int64), 0),
|
||||
}
|
||||
|
||||
return s.db.Create(revokedToken).Error
|
||||
}
|
||||
|
||||
func (s *TokenService) IntrospectToken(token, tokenTypeHint string) (*TokenInfo, error) {
|
||||
// 检查令牌是否被撤销
|
||||
var revokedToken RevokedToken
|
||||
if err := s.db.Where("token = ?", token).First(&revokedToken).Error; err == nil {
|
||||
return &TokenInfo{Active: false}, nil
|
||||
}
|
||||
|
||||
// 解析令牌
|
||||
claims, err := s.parseToken(token)
|
||||
if err != nil {
|
||||
return &TokenInfo{Active: false}, nil
|
||||
}
|
||||
|
||||
// 检查令牌是否过期
|
||||
exp := time.Unix(claims["exp"].(int64), 0)
|
||||
if time.Now().After(exp) {
|
||||
return &TokenInfo{Active: false}, nil
|
||||
}
|
||||
|
||||
// 构建令牌信息
|
||||
info := &TokenInfo{
|
||||
Active: true,
|
||||
Scope: claims["scope"].(string),
|
||||
ClientID: claims["iss"].(string),
|
||||
TokenType: "Bearer",
|
||||
Exp: claims["exp"].(int64),
|
||||
Iat: claims["iat"].(int64),
|
||||
Sub: claims["sub"].(string),
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (s *TokenService) parseToken(token string) (jwt.MapClaims, error) {
|
||||
parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return s.keyManager.GetPrivateKey().Public(), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid {
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
|
||||
func (s *TokenService) AutoMigrate() error {
|
||||
return s.db.AutoMigrate(&RevokedToken{})
|
||||
}
|
||||
Reference in New Issue
Block a user