diff --git a/webserver/authmod/jwt.go b/webserver/authmod/jwt.go new file mode 100644 index 0000000..0d2e8e7 --- /dev/null +++ b/webserver/authmod/jwt.go @@ -0,0 +1,50 @@ +package authmod + +import ( + "time" + + "github.com/coreos/go-oidc" + "github.com/golang-jwt/jwt/v4" + "github.com/google/uuid" +) + +type AuthTokenClaims struct { + jwt.RegisteredClaims // 표준 토큰 Claims + UserInfo *oidc.UserInfo +} + +var TknHmacSecret []byte = nil + +func init() { + TknHmacSecret = []byte(uuid.New().String()) +} + +func IssueJWT(userInfo *oidc.UserInfo, period time.Duration) (string, error) { + claims := AuthTokenClaims{ + UserInfo: userInfo, + RegisteredClaims: jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(time.Now().Add(period)), + IssuedAt: jwt.NewNumericDate(time.Now()), + NotBefore: jwt.NewNumericDate(time.Now()), + }, + } + + tkn := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + ss, err := tkn.SignedString([]byte(TknHmacSecret)) + + return ss, err +} + +func ParseJWTwithClaims(ss string) (*AuthTokenClaims, error) { + claims := AuthTokenClaims{} + + _, err := jwt.ParseWithClaims(ss, &claims, func(token *jwt.Token) (interface{}, error) { + return TknHmacSecret, nil + }) + + if err != nil { + return nil, err + } + + return &claims, nil +} diff --git a/webserver/router/auth.go b/webserver/router/auth.go index 47feae7..cafb677 100644 --- a/webserver/router/auth.go +++ b/webserver/router/auth.go @@ -4,7 +4,9 @@ import ( "context" "crypto/rand" "encoding/base64" + "fmt" "io" + "iothomepage/authmod" "log" "net/http" "time" @@ -93,11 +95,17 @@ func authCallback(ctx *gin.Context) { return } - _ = userInfo + ss, err := authmod.IssueJWT(userInfo, time.Second) + if err != nil { + http.Error(ctx.Writer, "generate jwt error", http.StatusInternalServerError) + return + } + + fmt.Println(userInfo) c := &http.Cookie{ Name: "__edit_access_token_", - Value: "temporary-token", + Value: ss, MaxAge: int(time.Hour.Seconds()), Secure: ctx.Request.TLS != nil, HttpOnly: true, diff --git a/webserver/router/route.go b/webserver/router/route.go index 8cf34c9..47a21f3 100644 --- a/webserver/router/route.go +++ b/webserver/router/route.go @@ -2,6 +2,7 @@ package router import ( "fmt" + "iothomepage/authmod" "log" "net/http" "strings" @@ -28,7 +29,7 @@ func NewRouter() *gin.Engine { r.Any("/*any", func(c *gin.Context) { defer handleError(c) path := c.Param("any") - if strings.HasPrefix(path, "/home") { + if strings.HasPrefix(path, "/dashboard") { assetEngine.HandleContext(c) return } else if strings.HasPrefix(path, "/auth") { @@ -70,8 +71,12 @@ func checkAuthority(c *gin.Context) bool { return false } - // editAuth check - _ = editAuth + claims, err := authmod.ParseJWTwithClaims(editAuth) + if err != nil { + return false + } + + fmt.Println(claims.UserInfo) return true }