Use JWT access tokens

This commit is contained in:
Melon 2024-02-10 16:23:07 +00:00
parent 23a49e5a6a
commit b6d5bef56c
Signed by: melon
GPG Key ID: 6C9D970C50D26A25
2 changed files with 36 additions and 2 deletions

35
server/jwt.go Normal file
View File

@ -0,0 +1,35 @@
package server
import (
"context"
"crypto/sha256"
"encoding/base64"
"github.com/1f349/mjwt"
"github.com/1f349/mjwt/auth"
"github.com/go-oauth2/oauth2/v4"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"strings"
)
type JWTAccessGenerate struct {
signer mjwt.Signer
}
func NewJWTAccessGenerate(signer mjwt.Signer) *JWTAccessGenerate {
return &JWTAccessGenerate{signer}
}
var _ oauth2.AccessGenerate = &JWTAccessGenerate{}
func (j JWTAccessGenerate) Token(ctx context.Context, data *oauth2.GenerateBasic, isGenRefresh bool) (access, refresh string, err error) {
access, err = j.signer.GenerateJwt(data.UserID, "", jwt.ClaimStrings{data.Client.GetID()}, data.TokenInfo.GetAccessExpiresIn(), auth.AccessTokenClaims{})
if isGenRefresh {
t := uuid.NewHash(sha256.New(), uuid.New(), []byte(access), 5).String()
refresh = base64.URLEncoding.EncodeToString([]byte(t))
refresh = strings.ToUpper(strings.TrimRight(refresh, "="))
}
return
}

View File

@ -14,7 +14,6 @@ import (
scope2 "github.com/1f349/tulip/scope"
"github.com/1f349/tulip/theme"
"github.com/go-oauth2/oauth2/v4/errors"
"github.com/go-oauth2/oauth2/v4/generates"
"github.com/go-oauth2/oauth2/v4/manage"
"github.com/go-oauth2/oauth2/v4/server"
"github.com/go-oauth2/oauth2/v4/store"
@ -86,7 +85,7 @@ func NewHttpServer(conf Conf, db *database.DB, signingKey mjwt.Signer) *http.Ser
oauthManager.SetAuthorizeCodeTokenCfg(manage.DefaultAuthorizeCodeTokenCfg)
oauthManager.MustTokenStorage(store.NewMemoryTokenStore())
oauthManager.MapAccessGenerate(generates.NewAccessGenerate())
oauthManager.MapAccessGenerate(NewJWTAccessGenerate(hs.signingKey))
oauthManager.MapClientStorage(clientStore.New(db))
oauthSrv.SetResponseErrorHandler(func(re *errors.Response) {