Skip to content

feat: JWT認証のリフレッシュトークンと有効期限のトークンの処理ロジック - #153

Open
Justhiro55 wants to merge 3 commits into
developfrom
feature/jwt-auth-improvements
Open

Justhiro55 wants to merge 3 commits into
developfrom
feature/jwt-auth-improvements

Conversation

@Justhiro55

@Justhiro55 Justhiro55 commented Jul 14, 2025 •

Copy link
Copy Markdown
Collaborator

概要

#149
JWT認証システムを改善.
リフレッシュトークン機能,ログアウト処理を実装してセキュリティ周り修正しました.

変更点

  • リフレッシュトークン機能の実装: 7日間有効なリフレッシュトークンで自動トークン更新を可能に
  • ログアウト処理の実装: /logoutエンドポイントでアクセストークンとリフレッシュトークンの両方を削除
  • トークンリフレッシュエンドポイント追加: /refreshで期限切れ前のトークン更新が可能
  • JWT有効期限の最適化: アクセストークン2時間、リフレッシュトークン7日間の適切な設定
  • 認証エラーハンドリングの改善: auth.IssueUserTokenとauth.IssueRefreshTokenのエラー処理を追加

@Justhiro55
Justhiro55 requested a review from Copilot July 15, 2025 01:28

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull Request Overview

This PR enhances the JWT authentication flow by adding refresh-token support, logout handling, and tuning token lifetimes.

  • Extend Login to issue both access and refresh tokens, plus a new RefreshToken usecase method
  • Introduce refresh-token claims, issuance, and verification in app/packages/utils/auth/user.go
  • Add /logout and /refresh routes and handlers, setting/clearing cookies appropriately

Reviewed Changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
app/usecase/auth.go Updated Login signature, error wrapping, and added RefreshToken
app/packages/utils/auth/user.go Defined refreshTokenClaims and implemented Issue/VerifyRefreshToken
app/interfaces/server.go Registered /logout and /refresh HTTP routes
app/interfaces/handler/auth.go Updated SignIn to set refresh cookie, added Logout, CheckAuth, RefreshToken handlers
app/configs/config.go Imported strings and added IsProduction helper
Comments suppressed due to low confidence (4)

app/interfaces/handler/auth.go:278

  • Specify Path: "/" on the refreshed access-token cookie so it's sent with all routes, not just the current path.
	cookie := &http.Cookie{

app/interfaces/server.go:86

  • Add unit or integration tests for the new /logout endpoint to verify cookies are cleared correctly.
	s.Router.Post("/logout", authHandler.Logout)

app/interfaces/server.go:88

  • Add tests for the /refresh endpoint to cover valid, missing, and expired/invalid refresh-token scenarios.
	s.Router.Post("/refresh", authHandler.RefreshToken)

app/usecase/auth.go:102

  • Add a doc comment for RefreshToken describing its behavior, inputs, and returned values.
func (a *AuthUseCase) RefreshToken(refreshToken string) (string, error) {

Comment thread app/usecase/auth.go Outdated
Comment on lines +91 to +96
return nil, "", "", errors.New("failed to generate JWT token")
}

refreshToken, err := auth.IssueRefreshToken(user.UserID)
if err != nil {
return nil, "", "", errors.New("failed to generate refresh token")

Copilot AI Jul 15, 2025

Copy link

Choose a reason for hiding this comment

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

Wrap the original error when JWT issuance fails (e.g., fmt.Errorf("failed to generate JWT token: %w", err)) to preserve context.

Suggested change
return nil, "", "", errors.New("failed to generate JWT token")
}
refreshToken, err := auth.IssueRefreshToken(user.UserID)
if err != nil {
return nil, "", "", errors.New("failed to generate refresh token")
return nil, "", "", fmt.Errorf("failed to generate JWT token: %w", err)
}
refreshToken, err := auth.IssueRefreshToken(user.UserID)
if err != nil {
return nil, "", "", fmt.Errorf("failed to generate refresh token: %w", err)

Copilot uses AI. Check for mistakes.
Comment thread app/usecase/auth.go Outdated

refreshToken, err := auth.IssueRefreshToken(user.UserID)
if err != nil {
return nil, "", "", errors.New("failed to generate refresh token")

Copilot AI Jul 15, 2025

Copy link

Choose a reason for hiding this comment

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

Wrap the underlying error when refresh-token issuance fails (e.g., fmt.Errorf("failed to generate refresh token: %w", err)).

Suggested change
return nil, "", "", errors.New("failed to generate refresh token")
return nil, "", "", fmt.Errorf("failed to generate refresh token: %w", err)

Copilot uses AI. Check for mistakes.
}

var refreshTokenJwt = &hs256jwt{
sigKey: []byte("SKNGIonriongINIOnfiar394rjOJGg"),

Copilot AI Jul 15, 2025

Copy link

Choose a reason for hiding this comment

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

Avoid hardcoding JWT signing keys in source; load this secret from configuration or environment variables.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

.env作成は別タスクに切り分けるのでここではハードコーディングの状態を許容することにします

Comment thread app/packages/utils/auth/user.go Outdated
if c.Exp < now.Unix() {
return fmt.Errorf("token expired: %d (now:%d)", c.Exp, now.Unix())
}
if c.TokenType != "refresh" {

Copilot AI Jul 15, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] Define a constant for the token type string (e.g., const RefreshTokenType = "refresh") instead of hardcoding it.

Suggested change
if c.TokenType != "refresh" {
if c.TokenType != RefreshTokenType {

Copilot uses AI. Check for mistakes.
}

// アクセストークンをクッキーに設定
cookie := &http.Cookie{

Copilot AI Jul 15, 2025

Copy link

Choose a reason for hiding this comment

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

Set HttpOnly: true, Path: "/", and consider SameSite and Secure attributes on the access-token cookie to improve security.

Copilot uses AI. Check for mistakes.
Comment thread app/interfaces/handler/auth.go Outdated

// リフレッシュトークンを別のクッキーに設定
refreshCookie := &http.Cookie{
Name: "refresh_token",

Copilot AI Jul 15, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] Centralize cookie names ("token", "refresh_token") into package-level constants to reduce duplication and typos.

Suggested change
Name: "refresh_token",
Name: CookieRefreshToken,

Copilot uses AI. Check for mistakes.

@static-fuji static-fuji left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGMT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants