Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JWT発行API #462

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ services:
ORIGIN: http://localhost:6006
SESSION_KEY: ${SESSION_KEY:-random32wordsXXXXXXXXXXXXXXXXXXX}
TRAQ_CALENDARID: ${TRAQ_CALENDARID}
CLIENT_ID: ${CLIENT_ID:-aYj6mwyLcpBIrxZZD8jkCzH3Gsdqc9DJqle2}
CLIENT_ID: ${CLIENT_ID:-hhCZHJemBHaIPPYFxBLElXnOG2X8jelWLCyj}
WEBHOOK_ID: ${WEBHOOK_ID}
WEBHOOK_SECRET: ${WEBHOOK_SECRET}
CHANNEL_ID: ${CHANNEL_ID}
Expand Down
17 changes: 17 additions & 0 deletions docs/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,23 @@ paths:
responses:
'302':
description: 成功。/callbackにリダイレクト。(その後はuiがリダイレクトする)
/token:
post:
tags:
- authentication
operationId: createToken
description: APIトークンを発行します。
responses:
'201':
description: 成功
content:
application/json:
schema:
type: object
properties:
token:
type: string
description: APIトークン(JWT)

/ical/v1/{icalToken}:
get:
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ require (
github.com/go-gormigrate/gormigrate/v2 v2.1.0
github.com/go-sql-driver/mysql v1.7.1
github.com/gofrs/uuid v4.4.0+incompatible
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/gorilla/securecookie v1.1.1
github.com/gorilla/sessions v1.2.1
github.com/jinzhu/copier v0.3.5
github.com/jszwec/csvutil v1.8.0
github.com/labstack/echo-contrib v0.15.0
github.com/labstack/echo-jwt/v4 v4.2.0
github.com/labstack/echo/v4 v4.11.1
github.com/ory/dockertest/v3 v3.10.0
github.com/patrickmn/go-cache v2.1.0+incompatible
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
Expand Down Expand Up @@ -143,6 +145,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/labstack/echo-contrib v0.15.0 h1:9K+oRU265y4Mu9zpRDv3X+DGTqUALY6oRHCSZZKCRVU=
github.com/labstack/echo-contrib v0.15.0/go.mod h1:lei+qt5CLB4oa7VHTE0yEfQSEB9XTJI1LUqko9UWvo4=
github.com/labstack/echo-jwt/v4 v4.2.0 h1:odSISV9JgcSCuhgQSV/6Io3i7nUmfM/QkBeR5GVJj5c=
github.com/labstack/echo-jwt/v4 v4.2.0/go.mod h1:MA2RqdXdEn4/uEglx0HcUOgQSyBaTh5JcaHIan3biwU=
github.com/labstack/echo/v4 v4.11.1 h1:dEpLU2FLg4UVmvCGPuk/APjlH6GDpbEPti61srUUUs4=
github.com/labstack/echo/v4 v4.11.1/go.mod h1:YuYRTSM3CHs2ybfrL8Px48bO6BAnYIN4l8wSTMP6BDQ=
github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8=
Expand Down
29 changes: 29 additions & 0 deletions router/authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ import (
"net/http"
"time"

"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/patrickmn/go-cache"
"github.com/traPtitech/knoQ/router/presentation"
"github.com/traPtitech/knoQ/utils/random"
)

const JWTSecret = "jwtsecret"

var verifierCache = cache.New(5*time.Minute, 10*time.Minute)
var stateCache = cache.New(5*time.Minute, 10*time.Minute)

Expand Down Expand Up @@ -79,3 +83,28 @@ func (h *Handlers) HandleCallback(c echo.Context) error {
}
return c.Redirect(http.StatusFound, "/callback")
}

func (h *Handlers) HandleCreateToken(c echo.Context) error {
sess, err := session.Get("session", c)
if err != nil {
setMaxAgeMinus(c)
return unauthorized(err, needAuthorization(true),
message("please try again"))
}

claims := jwt.RegisteredClaims{
Subject: sess.Values["userID"].(string),
ras0q marked this conversation as resolved.
Show resolved Hide resolved
ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * 24 * time.Hour)),
ras0q marked this conversation as resolved.
Show resolved Hide resolved
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

signedToken, err := token.SignedString([]byte(JWTSecret))
if err != nil {
return internalServerError(err)
}

return c.JSON(http.StatusOK, presentation.CreateTokenRes{
Token: signedToken,
})
}
26 changes: 26 additions & 0 deletions router/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strconv"
"time"

"github.com/golang-jwt/jwt/v5"
"github.com/traPtitech/knoQ/domain"
"github.com/traPtitech/knoQ/router/logging"
"github.com/traPtitech/knoQ/router/presentation"
Expand All @@ -16,6 +17,7 @@ import (
"go.uber.org/zap"

"github.com/labstack/echo-contrib/session"
echojwt "github.com/labstack/echo-jwt/v4"
"github.com/labstack/echo/v4"
)

Expand Down Expand Up @@ -80,6 +82,30 @@ func ServerVersionMiddleware(version string) echo.MiddlewareFunc {
}
}

func (h *Handlers) JWTMiddleware() echo.MiddlewareFunc {
return echojwt.WithConfig(
echojwt.Config{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Signing Methodは明示的に書いたほうがいい(デフォルト値だとわからないので)

SigningKey: []byte(JWTSecret),
SuccessHandler: func(c echo.Context) {
// jwtの検証に成功したらsessionにuserIDを保存
sess, _ := session.Get("session", c)
claims := c.Get("user").(*jwt.Token).Claims.(*jwt.RegisteredClaims)
sess.Values["userID"] = claims.Subject
sess.Options = &h.SessionOption
_ = sess.Save(c.Request(), c.Response())
},
ErrorHandler: func(c echo.Context, err error) error {
return nil
},
ContinueOnIgnoredError: true,
Comment on lines +97 to +100
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これがないとJWTないとき弾かれるんだけどこれを追加していいのか自信がない

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://github.com/traPtitech/knoQ/pull/462/files#diff-c399d26e7f23b713ce01946ac9e0e6f1fc94d692e8a086180191901da91b6964R61

単純にここの順番を入れ替えてしまうという手段がある(隠された実装に依存するけどたぶん配列回してるだけ)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

先に部員認証しちゃうとIDが入ってなくてトークン使えなさそう

ContextKey: "user",
NewClaimsFunc: func(c echo.Context) jwt.Claims {
return &jwt.RegisteredClaims{}
},
},
)
}

// TraQUserMiddleware traQユーザーか判定するミドルウェア
// TODO funcname fix
func (h *Handlers) TraQUserMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
Expand Down
5 changes: 5 additions & 0 deletions router/presentation/authorization.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package presentation

type CreateTokenRes struct {
Token string `json:"token"`
}
11 changes: 5 additions & 6 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@ func (h *Handlers) SetupRoute() *echo.Echo {
}))

// API定義 (/api)
api := e.Group("/api", h.TraQUserMiddleware)
api := e.Group("/api",
h.JWTMiddleware(),
h.TraQUserMiddleware,
)
{
previlegeMiddle := h.PrevilegeUserMiddleware

Expand Down Expand Up @@ -136,11 +139,7 @@ func (h *Handlers) SetupRoute() *echo.Echo {
apiTags.GET("", h.HandleGetTags)
}

// apiActivity := api.Group("/activity")
// {
// apiActivity.GET("/events", h.HandleGetEventActivities)
// }

api.POST("/token", h.HandleCreateToken)
}
e.POST("/api/authParams", h.HandlePostAuthParams)
e.GET("/api/callback", h.HandleCallback)
Expand Down